(Xcode Swift SpriteKit) 如何将精灵朝它面向的方向移动

(Xcode Swift SpriteKit) How do I move a sprite in the direction it is facing

我在屏幕中央有一个精灵,可以向左或向右旋转,这是通过触摸屏幕的左侧或右侧来确定的。

我想做的是让精灵不断向前移动,但始终朝着它所面对的方向。我知道如何使用 SKActions 等进行基本运动...但不知道我如何计算运动以在精灵旋转到的方向上连续?

数学从来都不是我的强项,所以非常感谢一些示例代码来帮助我。

var player = SKSpriteNode()

override func didMove(to view: SKView) {



    player = SKSpriteNode(imageNamed: "4B.png")
    player.setScale(0.3)
    player.zPosition = 100
    self.addChild(player)


}



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

    if let touch = touches.first {
        let position = touch.location(in: self)

        if position.x < 0 {
            let rotate = SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(M_PI), duration: 2))
            player.run(rotate, withKey: "rotating")
        } else {
            let rotate = SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(-M_PI), duration: 2))
            player.run(rotate, withKey: "rotating")
        }

    }

}



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

    player.removeAction(forKey: "rotating")
}



override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered

}

}

您将需要使用 sin 和 cos。 SKAction 可能对你来说不是最好的,所以我现在只在更新方法中这样做,直到你找到更好的位置:

sprite.position = CGPoint(x:sprite.position.x + cos(sprite.zRotation) * 10,y:sprite.position.y + sin(sprite.zRotation) * 10)

其中 10 是您希望精灵移动的幅度(即移动 10 个像素)

假设角度 0 表示精灵向右看,角度 90 (PI/2) 表示精灵向上看,角度 180 (PI) 表示精灵向左看,角度 270 (3PI/2)正在往下看。