Konrad Wright
Konrad Wright

Reputation: 1264

Rotate SpriteNode using shortest angle

Right now my code rotates _eye to look at _me but when _eye rotates from 359 degrees to 1 degrees it doesn't rotate by going 359 -> 0 -> 1, but it goes 359 -> 358 -> .. -> 2 -> 1.

#define SK_DEGREES_TO_RADIANS(__ANGLE__) ((__ANGLE__) * 0.01745329252f)
#define SK_RADIANS_TO_DEGREES(__ANGLE__) ((__ANGLE__) * 57.29577951f)

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    for (UITouch *touch in touches)
    {
        CGPoint location = [touch locationInNode:self];
        [_me runAction:[SKAction moveTo:location duration:0.5]];
    }
}

-(void)update:(CFTimeInterval)currentTime
{
    float deltaX = _me.position.x - _eye.position.x;
    float deltaY = _me.position.y - _eye.position.y;
    float angle = atan2f(deltaY, deltaX);

    [_eye runAction:[SKAction rotateToAngle:angle - SK_DEGREES_TO_RADIANS(90.0f) duration:0.2]];
}

Upvotes: 0

Views: 252

Answers (1)

0x141E
0x141E

Reputation: 12753

To rotate your sprite by the smallest angle, add shortestUnitArc to your SKAction:

[_eye runAction:[SKAction rotateToAngle:angle - SK_DEGREES_TO_RADIANS(90.0f) duration:0.2 shortestUnitArc:YES]];

From Apple's documentation,

shortestUnitArc

If YES, then the rotation is performed in whichever direction results in the smallest rotation. If NO, then the rotation is interpolated.

Upvotes: 2

Related Questions