问题
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