Vince
Vince

Reputation: 668

How to rotate a sprite node in sprite kit?

I am making a game and I'm having troubles with rotating a sprite node, This is the code I have; What do I have to add to turn it, let's say 45 degrees?.

SKSpriteNode *platform = [SKSpriteNode spriteNodeWithImageNamed:@"YellowPlatform.png"];
platform.position = CGPointMake(CGRectGetMidX(self.frame), -200+CGRectGetMidY(self.frame));
platform.size = CGSizeMake(180, 10);
platform.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:platform.size];
platform.physicsBody.dynamic = NO;
[self addChild:platform];

Upvotes: 25

Views: 42026

Answers (7)

quaertym
quaertym

Reputation: 3961

Just do this without using actions:

sprite.zRotation = M_PI / 4.0f;

And in Swift 4:

sprite.zRotation = .pi / 4

Upvotes: 75

Dave Levy
Dave Levy

Reputation: 1172

In Swift 4 the way I got mine to rotate was

sprite.zRotation =  .pi / 2 // 90 degrees
sprite.zRotation =  .pi / 4 // 45 degrees

Upvotes: 8

wm.p1us
wm.p1us

Reputation: 2059

For SWIFT 3 / SWIFT 4 version you could use next:

sprite.zRotation = .pi / 4

or if you like actions:

let rotateAction = SKAction.rotate(toAngle: .pi / 4, duration: 0)
sprite.run(rotateAction)

Upvotes: 6

Chigo Godwin Anyaso
Chigo Godwin Anyaso

Reputation: 209

//rotates player node 90 degrees
player.zRotation = CGFloat(M_PI_2)*3;
//rotates 180 degrees
player.zRotation = CGFloat(M_PI_2)*2;
//rotates 270 degrees
player.zRotation = CGFloat(M_PI_2)*1;
//rotates 360 degrees (where it was originally)
player.zRotation = CGFloat(M_PI_2)*4;
//rotates 315 degrees
player.zRotation = (CGFloat(M_PI_2)*1)/2;
and so on...

Upvotes: 3

J. V.
J. V.

Reputation: 376

sprite.zRotation = M_PI_4;

and

[sprite runAction:[SKAction rotateByAngle:M_PI_4 duration:0]];

are not the same.

running the SKAction will animate the change even if the duration is 0 it will do it over very short time. changing the zRotation will show it in the new rotation.

why this is important: if you add new sprite doing on it [SKAction rotateByAngle:] will create flickering/ugliness in the sprite as it comes on the view.

if the sprite is on the screen and you want to rotate it changing the zRotation will not be as nice as rotatebyAngle: even with 0 duration.

Upvotes: 15

ZeMoon
ZeMoon

Reputation: 20274

Using the predefined value will be faster:

sprite.zRotation = M_PI_4;

These predefined constants in math.h are available as literals and can be used to reduce actual processing of values like M_PI / 4.0

Upvotes: 13

BSevo
BSevo

Reputation: 793

You make SKAction for the rotation and run that action on the node. for example:

//M_PI/4.0 is 45 degrees, you can make duration different from 0 if you want to show the rotation, if it is 0 it will rotate instantly
SKAction *rotation = [SKAction rotateByAngle: M_PI/4.0 duration:0]; 
//and just run the action
[yourNode runAction: rotation];  

Upvotes: 20

Related Questions