SpriteKit moves physics with applyImpulse
I want to move a physical element with applyImpulse method in a direction based on the rotation of the physibody.
For example, a physical body is square in shape, I call "motion", which will apply momentum to make it move upward vertically. Then I call the method to rotate the physics 45 degrees to the right. If I call the "move" method again, the physics moves diagonally to the right and up.
Can anyone please help?
source to share
I suggest that you follow Sprite Kits' coordinating and rotational conventions. Specifically, your sprite image should be rotated straight to zero (the default), and a positive value should rotate counterclockwise. However, here's one way to apply momentum in the direction the 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)];
source to share
UPDATED:
Fixed with below, thanks to @ 0x141E
-(void)characterJump {
CGFloat radianFactor = 0.0174532925;
CGFloat rotationInDegrees = _body.zRotation / radianFactor;
CGFloat newRotationDegrees = rotationInDegrees + 90;
CGFloat newRotationRadians = newRotationDegrees * radianFactor;
CGFloat r = 500;
CGFloat dx = r * cos(newRotationRadians);
CGFloat dy = r * sin(newRotationRadians);
[_body.physicsBody applyImpulse:CGVectorMake(dx, dy)];
}
source to share