Marti Serra Vivancos
Marti Serra Vivancos

Reputation: 1179

SKSpriteNode rotation not working properly

I'm trying to rotate a SKSpriteNode by using UIRrotationGestureRecognizer. I've implemented a code but sometimes, when I rotate the node it jumps to a rotation that isn't the one it should be. Here you have the code:

- (void) handleRotation:(UIRotationGestureRecognizer *) rotationrecognizer{

    CGFloat initialrotation = 0.0;

    if (rotationrecognizer.state == UIGestureRecognizerStateBegan) {

      CGPoint touchLocation = [rotationrecognizer locationInView:rotationrecognizer.view];
      touchLocation = [self convertPointFromView:touchLocation];
      [self selectNodeForTouch:touchLocation];

      initialrotation = selected.zRotation;
    }

    else if (rotationrecognizer.state == UIGestureRecognizerStateChanged) {        

      CGFloat angle = initialrotation + rotationrecognizer.rotation;
      selected.zRotation = angle;      

   }   
}

Upvotes: 1

Views: 1582

Answers (1)

MobileVet
MobileVet

Reputation: 2958

You are resetting initial rotation to 0 on every call... you should move this to be an ivar of your view if you need it to stay resident.

The way you have it written now, the line that sets 'angle' is effectively equal to this:

CGFloat angle = 0 + rotationrecognizer.rotation;

Instead, you should do the following (where initialRotation is defined as a private ivar):

- (void) handleRotation:(UIRotationGestureRecognizer *) rotationrecognizer{

    if (rotationrecognizer.state == UIGestureRecognizerStateBegan) {

      CGPoint touchLocation = [rotationrecognizer locationInView:rotationrecognizer.view];
      touchLocation = [self convertPointFromView:touchLocation];
      [self selectNodeForTouch:touchLocation];

      _initialrotation = selected.zRotation;
    }

    else if (rotationrecognizer.state == UIGestureRecognizerStateChanged) {        

      CGFloat angle = _initialrotation + rotationrecognizer.rotation;
      selected.zRotation = angle;      

   }   
}

Upvotes: 3

Related Questions