使用游戏控制器 (ThumbStick) 移动 skspritenode Swift

Moving skspritenode with Game Controller (ThumbStick) Swift

我尝试构建 2d - 自上而下的游戏,我有玩家 (skspritenode),我想在使用摇杆时移动他。我使用此代码:

游戏手柄其 GCExtendedGamepad

if gamepad.leftThumbstick.xAxis.value > 0.1 || gamepad.leftThumbstick.xAxis.value < -0.1 || gamepad.leftThumbstick.yAxis.value > 0.1 || gamepad.leftThumbstick.yAxis.value < -0.1
{
    self.player.moveAndRotate(gamepad.leftThumbstick.xAxis.value, yValue: gamepad.leftThumbstick.yAxis.value)
}

moveAndRotate - 函数

func moveAndRotate(xValue: Float, yValue: Float)
{
    zRotation = CGFloat(-atan2(xValue, yValue))

    physicsBody!.velocity = CGVectorMake(0, 0)
    physicsBody!.applyImpulse(CGVectorMake(CGFloat(xValue) * moveSpeed, CGFloat(yValue) * moveSpeed))
}

但是,当玩家沿对角线移动时,他的速度比正常速度快。谁能帮帮我?

我确定你的三角函数是倒退的

这是我在游戏中用来沿对角线移动的代码片段。

let angle: CGFloat = atan2f(dest.y - self.position.y, dest.x - self.position.x)

y值在x值之前

引自Raywenderlich.com

对于这个具体的问题,不用atan(),使用函数atan2()更简单,它把x和y分量作为单独的参数,并正确地确定整体旋转角度。

angle = atan2(opposite, adjacent)

let angle = atan2(playerVelocity.dy, playerVelocity.dx)
playerSprite.zRotation = angle

注意 Y 坐标在前。一个常见的错误是写成 atan(x, y),但这是错误的做法。请记住,第一个参数是相反的一侧,在这种情况下,Y 坐标位于您要测量的角度的相反方向。

我能够重现您的问题,但是通过将代码更改为下面的代码,我能够使对角线移动的速度与上下移动的速度相同

if ((!isDPad && dirPad.up.value > 0.2) || (isDPad && dirPad.up.pressed == true)) { self.upValue = 1 //upValue = gamepad.leftThumbstick.up.value }

    if ((!isDPad && dirPad.down.value > 0.2) || (isDPad && dirPad.down.pressed == true)) {
        self.downValue = 1
    }

    if ((!isDPad && dirPad.right.value > 0.2) || (isDPad && dirPad.right.pressed == true)) {
        self.rightValue = 1
    }

    if ((!isDPad && dirPad.left.value > 0.2) || (isDPad && dirPad.left.pressed == true)) {
        self.leftValue = 1
    }

    let speed: Float = 300.0
    let xValue = self.rightValue - self.leftValue
    let yValue = self.upValue - self.downValue

    let length = hypotf(xValue, yValue)

    var moveDirection: CGVector?

    if length > 0.0 {
        let inverseLength = 1 / length
        moveDirection = CGVector(dx: CGFloat(xValue * inverseLength * speed), dy: CGFloat(yValue * inverseLength * speed))
    }
    else {
        moveDirection = CGVector(dx: 0, dy: 0)
    }

    testObject.physicsBody!.velocity = CGVectorMake(0, 0)
    testObject.physicsBody!.applyImpulse(direction)