Search code examples
objective-csprite-kitpolygonskphysicsbody

Creating a SKPhysicsBody on a triangular sprite


I have a sprite that looks like this.

enter image description here

How would I create an SKPhysicsBody for this sprite? I want it so that the SKPhysicsBody either is a triangle or it is just an edge on the long side of the sprite. Here is what I have so far. The sprite, called rightEnemy, has an anchor point of

CGPointMake(0.5, 0.5);
rightEnemy.physicsBody = [SKPhysicsBody bodyWithEdgeFromPoint:CGPointMake(rightEnemy.position.x + width, rightEnemy.position.y) toPoint:CGPointMake(rightEnemy.position.x, rightEnemy.position.y + height)];

This creates a physics body but for some reason it is not attached to the sprite.

The sprite that the physics body is attached to is moving constantly via the update method. The y value is always changing.


Solution

  • You may want to try to create the physical body from the texture.

    rightEnemy.physicsBody = [SKPhysicsBody bodyWithTexture:rightEnemy.texture size:rightEnemy.size];
    

    You can also do this to validate if the physics is set correctly.

    self.scene.view.showsPhysics = YES;
    

    Edit

    For iOS 7

    Untested but I would imagine the bodyWithEdgeFromPoint: needs to be in the sprites coordinate system. You could try this which "should" draw a line from the bottom left to the top right corners of your sprite.

    rightEnemy.physicsBody = [SKPhysicsBody bodyWithEdgeFromPoint:CGPointMake(-rightEnemy.size.width/2, -rightEnemy.size.height/2) toPoint:CGPointMake(rightEnemy.size.width/2, rightEnemy.size.height/3)];
    

    Hopefully that helps.