3
votes
    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?

4
Do note, that didBeginContact will fire multiple times due to their being multiple contact points, you will have to handle this in code - Knight0fDragon

4 Answers

1
votes

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

0
votes

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.

0
votes

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)
0
votes

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())
}