Cj Miller
Cj Miller

Reputation: 55

Rotating Sprites Using Swift

I am trying to rotate a sprite by let's say 90 degrees. How would I code this? I tried this

let rotate = [SKAction .rotateByAngle(M_PI_4, duration: 0)]

but that gave me an error.M

Upvotes: 0

Views: 98

Answers (2)

Whirlwind
Whirlwind

Reputation: 13665

M_PI_4 is defined as Double and SKAction.rotateByAngle: duration: takes CGFloat for angle parameter.

Try this:

import SpriteKit


class GameScene: SKScene {



    override func didMoveToView(view: SKView) {


        let object = SKSpriteNode(color: SKColor.greenColor(), size: CGSize(width: 100.0, height: 100.0))
        object.position = CGPoint(x: CGRectGetMidX(frame), y:CGRectGetMidY(frame))
        addChild(object)

        let rotate = SKAction.rotateByAngle(CGFloat(M_PI_4), duration:0) //You need explicit cast here , M_PI_4 is defined as Double



        //First way
        object.runAction(rotate)

        //Second way

        object.zRotation = CGFloat(M_PI_2)

    }


}

Upvotes: 0

Joseph Lord
Joseph Lord

Reputation: 6504

M_PI_4 is of type Double but the function takes a CGFloat so you need to cast it.

let rotate = [SKAction.rotateByAngle(CGFloat(M_PI_4), duration: 0)]

Note that rotate will at this point be an array of a single SKAction. Remove the square brackets if that isn't what you want and you just want the SKAction itself.

CGFloat is a floating point type used in most of the UI libraries. The precision depends on the platform. In general on 32bit devices it is equivalent to Float and on 64 bit devices it is equivalent to Double.

Upvotes: 1

Related Questions