SpriteKit物理体非矩形碰撞

3
    pipeUp.physicsBody = SKPhysicsBody(rectangleOfSize: pipeUp.size)

在这段代码中,我使用了rectangleOfSize来进行碰撞物理体的处理,但如果我想使用图像本身的像素形状进行处理,我应该使用什么替代rectangleOfSize呢?


请注意,由于存在多个接触点,didBeginContact 会触发多次,您需要在代码中处理这个问题。 - Knight0fDragon
4个回答

1

您需要创建一个CGPath,该路径应该是您对象的形状,并使用SKPhysicsBodyinit(polygonFromPath path: CGPath),具体操作在此处描述


0
您可以基于纹理创建物理体:
pipeUp.physicsBody = SKPhysicsBody(texture:pipeUp.texture)  

它会为你创建一个alpha遮罩纹理,因此任何alpha值为0的像素都不会被包含在物理体内。
编辑:
@classenApps让我意识到我制作了一个扩展来完成这个功能,所以我会加上它,以使答案正确。
extension SKPhysicsBody
{
    convenience init(texture: SKTexture)
    self.init(texture:texture,size:texture.size())
}

0
我会使用KnightOfDragon的方法,并加上size参数,像这样:
pipeUp.physicsBody = SKPhysicsBody(texture: pipeUp.texture, size: pipeUp.size)

我相信使用 CGPath 存在/曾经存在内存泄漏问题。


实际上,你的方法是正确的,基于AppleDocs,我有一个扩展可以在不改变大小的情况下完成它。 - Knight0fDragon

0
如果您需要明确告诉纹理使用什么alphaThreshold,另一个解决方案可以是:
/**
     Creates a body from the alpha values in the supplied texture.
     @param texture the texture to be interpreted
     @param alphaThreshold the alpha value above which a pixel is interpreted as opaque
     @param size of the generated physics body
     */
    @available(iOS 8.0, *)
    public /*not inherited*/ init(texture: SKTexture, alphaThreshold: Float, size: CGSize)

那么代码将会是:

pipeUp.physicsBody = SKPhysicsBody(texture: pipeUp.texture, alphaThreshold: 0.3, size: pipeUp.size)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接