以更改的度数旋转SKSpritenode

时间:2017-01-28 16:10:18

标签: sprite-kit swift3 skspritenode skaction

如何定义SKAction,然后更新我的节点将旋转的度数?我试图用变量定义它,但是当我更新变量值时,动作不会更新。

var degreesToRotate = 4
var direction = 1

let action = SKAction.rotate(byAngle: CGFloat(degreesToRotate * direction), duration: TimeInterval(2))
            charector.run(SKAction.repeatForever(action))

direction = -1

1 个答案:

答案 0 :(得分:2)

import SpriteKit
import GameplayKit

//Extensions borrowed from here : http://stackoverflow.com/a/29179878/3402095

extension Int {
    var degreesToRadians: Double { return Double(self) * .pi / 180 }
    var radiansToDegrees: Double { return Double(self) * 180 / .pi }
}
extension FloatingPoint {
    var degreesToRadians: Self { return self * .pi / 180 }
    var radiansToDegrees: Self { return self * 180 / .pi }
}

let kActionKey = "rotate"

class GameScene:SKScene {

    let purpleCube = SKSpriteNode(color: .purple, size: CGSize(width: 150, height: 150))
    let yellowCube = SKSpriteNode(color: .yellow, size: CGSize(width: 150, height: 150))

    override func didMove(to view: SKView) {


        addChild(purpleCube)
        purpleCube.position.y = purpleCube.size.height
        purpleCube.name = "purple"


        addChild(yellowCube)
        yellowCube.position.y = -yellowCube.size.height
        yellowCube.name = "yellow"

        let rotate = SKAction.rotate(byAngle: CGFloat(-M_PI * 2.0), duration: 5)
        let loop = SKAction.repeatForever(rotate)
        purpleCube.run(loop, withKey: kActionKey)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        super.touchesBegan(touches, with: event)


        if let touch = touches.first {

            let location = touch.location(in: self)

            if let cube = atPoint(location) as? SKSpriteNode {

                if let name = cube.name {

                    switch name {

                    case "purple":

                        if let action = purpleCube.action(forKey: kActionKey){

                            purpleCube.run(action.reversed(), withKey: kActionKey)
                        }


                    case "yellow":

                        if action(forKey: "rotating") == nil{
                           yellowCube.run(SKAction.rotate(byAngle: CGFloat(4.degreesToRadians), duration: 0.1), withKey: kActionKey)
                        }



                    default:
                        break
                    }
                }

            }
        }

    }
}

在此示例中,有两个节点以两种不同的方式旋转。紫色节点以顺时针方向以一定速度恒定旋转。为了实现这一点,我创建了一个将精灵旋转360度的动作......这将是一次革命,它将永远重复,因此精灵将永远旋转。

关于黄色节点...每次点击它都会旋转4度。目前你必须等待精灵停止旋转,以便你可以旋转更多。这是可选的,当然,我只想向您展示动作键的用处。

轮换方向

因为在SpriteKit中0度指定正x轴而正角度在逆时针方向,所以我将紫色立方体旋转-360度,这使精灵顺时针方向旋转。要了解有关SpriteKit坐标系的更多信息,请阅读this documentation section

Radians Vs Degrees

正如你所看到的,我说的是度数,而不是弧度...这是因为它很难说,我将精灵旋转了6.2831853072弧度:)这就是为什么我使用扩展转换从度到弧度,反之亦然。您可能经常使用它,所以我为您添加了它们。