2016-06-17 23 views
1

我嘗試構建2d - 自上而下的遊戲,並且我有玩家(skspritenode),當我使用拇指杆時我想移動他。我用這個代碼:用遊戲控制器(ThumbStick)移動skspritenode Swift

手柄的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)) 
} 

但是,當對角線的球員動作,他的速度比正常快的速度。誰能幫我?

回答

1

我相信,你的三角函數是向後

下面是代碼,我在遊戲中使用斜角移動片段。

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

y值來自Raywenderlich.com

引述對於這個特定的問題的x值

之前,而不是使用ATAN(),它是simplier使用函數atan2() ,它將x和y分量作爲單獨的參數,並正確確定整體旋轉角度。

angle = atan2(opposite, adjacent) 

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

請注意,Y座標先走。一個常見的錯誤是寫atan(x,y),但這是錯誤的。記住第一個參數是相反的一面,在這種情況下,Y座標與您要測量的角度相反。

我能,而是通過代碼更改爲下面我能夠有對角線移動一個相同的速度向上和向下

如果((!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) 
+0

感謝您提供此信息!但是,我問如何以相同的速度移動我的播放器:) – DonMugad

+0

查看我的編輯 –

+0

非常感謝! – DonMugad