Search code examples
iosrotationsprite-kitgame-physics

Rotation of Sprite in touch event


How am i able to rotate a SpriteNode in the touch event?

Here the code that've got so far:

 // Detect what side of the screen the user has touched.
 if(touchLocation.x < 160) { 
   // They've touched the left side (the car turns  left)
   [car runAction:[SKAction rotateByAngle:-50 duration:0]];
   [car.physicsBody applyImpulse:CGVectorMake(-20,0)];
   car.physicsBody.velocity = CGVectorMake(-20, 0);

 }else{
   // They've touched the right side (the car turns right)
   [car runAction:[SKAction rotateByAngle:50 duration:0]];
   [car.physicsBody applyImpulse:CGVectorMake(20,0)];
   _bird.physicsBody.velocity = CGVectorMake(20, 0);
 }

The rotation for -50 doesn't work, even though other Stackoverflow questions have given that as an accepted answer. Also the working normal 50 degree turn seems to work for a split second then revert back to its original place.

How would I get the rotation to stick and rotate smoothly?


Solution

  • when you use rotateByAngle it's in radians. theres about ~6 radians in a circle. so you're rotating this sprite many times over. It isn't a 50 degree turn the way you'd expect. You need to be using variations of CGFloat(M_PI). If you want to convert between degrees and radians the conversion is

    let radians = CGFloat(M_PI) * degrees / 180.0
    

    start there and then see if the sprite behaves in a more predictable way

    since your duration for your animation is 0 there is really no reason to use an action there.. can you just set

    car.zRotation = radians