SpriteKit PhysicsBody non-rectangular collision

╄→尐↘猪︶ㄣ 提交于 2019-12-12 13:15:49

问题


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

in this coding I used the rectangleOfSize for collision physics body, but if I want to use by pixel just the shape of the image, what I should use instead of rectangleOfSize?


回答1:


You should make a CGPath that is the shape of your object, and use SKPhysicsBody's init(polygonFromPath path: CGPath) as described here




回答2:


I'd use KnightOfDragon's method with the addition of the size: parameter like this:

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

I believe there is/used to be a memory leak using the CGPath.




回答3:


If you need to explicitly tell the texture what alphaThreshold to use, another solution can be:

/**
     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)

So the code will be:

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



回答4:


You can create a physics body based on the texture:

pipeUp.physicsBody = SKPhysicsBody(texture:pipeUp.texture)  

It will create an alpha mask texture for you, so any pixel that has an alpha 0, will not be included in the physics body.

Edit:

@classenApps made me realize I made an extension to do this, so I will add it for the answer to be correct.

extension SKPhysicsBody
{
    convenience init(texture: SKTexture)
    self.init(texture:texture,size:texture.size())
}


来源:https://stackoverflow.com/questions/38436882/spritekit-physicsbody-non-rectangular-collision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!