Search code examples
iossprite-kitphysicsskphysicsbody

SpriteKit move rotated physicsBody with applyImpulse


I want to move a physicsBody with the applyImpulse method in a direction based on the physicsBody rotation.

Foe example, the physicsBody is a square in shape, I call a "move" which will apply an impulse to make it move up vertically. I then call a method to rotate the physicsBody 45 degrees right. If I call the "move" method again, the physicsBody will move diagonally right and up.


Solution

  • I suggest that you follow Sprite Kit’s coordinate and rotation conventions. Specifically, your sprite image should be facing right at zero degrees (the default value), and a positive value is a counter-clockwise rotation. That said, here's one way to apply an impulse in the direction a sprite is facing:

    // Specify the force to apply to the SKPhysicsBody
    CGFloat r = 5;
    
    // Create a vector in the direction the sprite is facing
    CGFloat dx = r * cos (sprite.zRotation);
    CGFloat dy = r * sin (sprite.zRotation);
    
    // Apply impulse to physics body
    [sprite.physicsBody applyImpulse:CGVectorMake(dx,dy)];