(Xcode Swift SpriteKit) 如何在精灵面对的方向上移动精灵

Car*_*ton 3 sprite-kit skaction swift3

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

我想要做的是让精灵不断向前移动,但始终朝着它所面对的方向移动。我知道如何使用 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

}
Run Code Online (Sandbox Code Playgroud)

}

Kni*_*gon 5

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

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) 向下看。