Search code examples
objective-crotationtouchsprite-kitimage-rotation

How can I rotate image/sprite with touch on spriteKit?


I am trying to make a sprite rotate with one finger touch. Honestly, i have no idea how to do it, new to spriteKit. Any ideas?


Solution

  • This would rotate the sprite to where you touch using an action. If you'd want it to rotate while dragging the finger. You should remove the action and do the calculation on the touchesMoved: instead.

    -(void)didMoveToView:(SKView *)view {
        sprite = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"];
    
        sprite.xScale = 0.5;
        sprite.yScale = 0.5;
        sprite.position = CGPointMake(self.frame.size.width / 2, self.frame.size.height/2);
    
        [self addChild:sprite];
    }
    
    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        for (UITouch *touch in touches) {
            CGPoint location = [touch locationInNode:self];
    
    
            float dY = sprite.position.y - location.y;
            float dX = sprite.position.x - location.x;
            float angle = atan2f(dY, dX) + 1.571f;
            [sprite runAction:[SKAction rotateToAngle:angle duration:0.5 shortestUnitArc:YES]];
            return;
        }
    }
    

    Alternatively: (Remember to remove the code from the touchesBegan:

    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
        for (UITouch *touch in touches) {
            CGPoint location = [touch locationInNode:self];
    
            float dY = sprite.position.y - location.y;
            float dX = sprite.position.x - location.x;
            float angle = (atan2f(dY, dX)) + 1.571f;
            sprite.zRotation = angle;
        }
    }