user4202109
user4202109

Reputation:

How to apply force at an speicific angle in spriteKit?

I want to give Force to my SKSpriteNode at specific angle. So, How to treat my CGVector for give force at specific angle?

I had searched for it but unfortunately not getting any good way.

What i wants to achieve :

My SKSpriteNode moving towards the screen. There are buttons on top like 30,45,60. So if user press button(i.e. that Button contain "30") then i had to move my SKSpriteNode to 30 degree with same speed.

Please help me towards it if any of you can help me regarding this.

Upvotes: 5

Views: 1517

Answers (1)

0x141E
0x141E

Reputation: 12773

First, you will need to convert the angle in degrees to radians by multiplying it by pi / 180

CGFloat angleInRadians = angleInDegrees * M_PI / 180;

You can then determine the vector components in that direction by

CGFloat dx = cosf(angleInRadians);
CGFloat dy = sinf(angleInRadians);

and finally apply a force to the sprite with

[sprite.physicsBody applyForce:CGVectorMake(dx*scale, dy*scale)];

where scale determines how much force is applied.

Optionally, you can rotate the sprite to face in the same direction as its motion by

sprite.zRotation = angleInRadians + offset;

where offset is the difference in angle, in radians, between your sprite's image and zero degrees. For example, if your sprite is facing up when zRotation is zero, offset should be -M_PI_2.

Upvotes: 4

Related Questions