【问题标题】:How to move SpriteNode by its angle?如何按角度移动 SpriteNode?
【发布时间】:2019-06-02 17:10:55
【问题描述】:

我正在尝试创建一个小游戏,其中 SpriteNode(又名 Player)以恒定速度垂直向上移动。我想用它的角度来左右转向。但是,我无法使用播放器的角度正确移动它。

感谢您的宝贵时间。

这是我写的部分代码:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
            let location = touch.previousLocation(in: self)
        if location.x < self.size.width / 2 && location.y < self.size.height / 2 {
            // Turn Left
            print("TURNING LEFT")
            turn(left: true)
         } else if location.x >= self.size.width / 2 && location.y < self.size.height / 2 {
            // Turn Right
            print("TURNING RIGHT")
            turn(left: false)
         } else if location.y > self.size.height / 2 {
            // Go Up
            print("GOING UP!")
            move()
         }
    }
}

func turn(left: Bool) {
    if left {
        // Turn Left
        let turnAction = SKAction.rotate(byAngle: 0.1, duration: 0.05)
        let repeatAction = SKAction.repeatForever(turnAction)
        player?.run(repeatAction)
    } else {
        // Turn Right
        let turnAction = SKAction.rotate(byAngle: -0.1, duration: 0.05)
        let repeatAction = SKAction.repeatForever(turnAction)
        player?.run(repeatAction)
    }
}

func move() {
    // Move Up
    let moveAction = SKAction.moveBy(x: 0, y: 15, duration: 0.5)
    let repeatAction = SKAction.repeatForever(moveAction)
    player?.run(repeatAction)
}

【问题讨论】:

  • 我建议使用三角函数。

标签: swift sprite-kit 2d-games skaction


【解决方案1】:

使用三角函数,您可以确定精灵在任一方向上的 x 和 y 速度,为精灵指向的角度创建一个角度。可以在 here 找到一篇总结如何做到这一点的精彩文章。

如果您只是希望从字面上旋转精灵,可以通过为旋转创建一个 SKAction 并在节点上运行该动作来完成。

// Create an action, duration can be changed from 0 so the user can see a smooth transition otherwise change will be instant.
SKAction *rotation = [SKAction rotateByAngle: M_PI/4.0 duration:0]; 
//Simply run the action.
[myNode runAction: rotation];

【讨论】:

  • 感谢您指导我的文章。我想出了如何应用三角计算来解决我的问题。赞赏。
【解决方案2】:

感谢@makertech81 链接,我能够编写以下有效的代码:

func move() {
    // Move Up
    let playerXPos = sin((player?.zRotation)!) * -playerSpeed
    let moveAction = SKAction.moveBy(x: playerXPos, y: playerSpeed, duration: 0.5)
    let repeatAction = SKAction.repeatForever(moveAction)
    player?.run(repeatAction)
}

基本上,因为我知道通过zRotation 的角度,而且我知道玩家将向 Y 移动多少,所以我能够计算出它的sin(即 X 值)。因此,moveAction 将被正确计算到其目的地。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    相关资源
    最近更新 更多