2015-09-10 120 views
0

我正在创建一个像涂鸦跳跃(没有加速计)的游戏。如何将节点移动到我使用Swift在SpriteKit中触摸的位置?

我一直在试图弄清楚这一点,但我似乎无法让它像我一直期待的那样顺利运行。

这里是我的代码为我的触摸功能:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { 
    for touch: AnyObject in touches { 
     let touchLocation = touch.locationInNode(self) 
     lastTouch = touchLocation 
    }  
} 

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { 
    for touch: AnyObject in touches { 
     let touchLocation = touch.locationInNode(self) 
     lastTouch = touchLocation 
    } 
} 

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { 
    lastTouch = nil 
} 

override func update(currentTime: CFTimeInterval) { 
    if let touch = lastTouch { 
     let impulseVector = CGVector(dx: 400, dy: 400) 
     player.physicsBody?.applyImpulse(impulseVector) 
    } 
} 
+0

请告诉我们您的意思由于它运行不顺利。如果您正在iOS模拟器上测试,那么它会运行得更慢(由于仿真),但在实际设备上运行得更好。 – Gliderman

+0

无论何时我点击屏幕,我的精灵只会以一种非常快的速度向上和向右移动。并倾向于保持模拟器屏幕的右侧。 –

+0

你想要做什么?我不知道你想如何控制它。像点击屏幕的这一边跳起来,并触摸到一侧的一侧?是的,向上和向右运动是x和y上的400冲动,你可能希望减慢它。 – Gliderman

回答

0

从我收集的东西,你想改变是基于在触摸被施加到玩家impulseVector。我可以想象的代码看起来像这样:

// At the top of your code 
let scale = 0.5 

// Update function 
override func update(currentTime: CFTimeInterval) { 
    if let touch = lastTouch { 
     let xOffset = (touch.x - player.position.x)*scale 
     let yOffset = (touch.y - player.position.y)*scale 
     let impulseVector = CGVector(dx: xOffset, dy: yOffset) 
     player.physicsBody?.applyImpulse(impulseVector) 
    } 
} 

这将拉动player节点了多个力进一步远离它是从触摸。如果您试图用相同的力量拉动玩家,无论他们在哪里(在这种情况下可能更有可能),您可以这样做:

// At the top of your code 
let xPlayerForce = 20 
let yPlayerForce = 30 

// Update function 
override func update(currentTime: CFTimeInterval) { 
    if let touch = lastTouch { 
     var xForce = 0.0 
     var yForce = 0.0 
     let xTouchOffset = (touch.x - player.position.x) 
     let yTouchOffset = (touch.y - player.position.y) 

     if xTouchOffset > 0.0 { 
      xForce = xPlayerForce 
     } else if xTouchOffset < 0.0 { 
      xForce = -xPlayerForce 
     } // else we do nothing 

     if yTouchOffset > 0.0 { 
      yForce = yPlayerForce 
     } // here you can choose whether you want it to push 
      // the player node down, using similar code from the 
      // above if statement 

     let impulseVector = CGVector(dx: xForce, dy: yForce) 
     player.physicsBody?.applyImpulse(impulseVector) 
    } 
} 
+0

这正是我需要的,谢谢! –

相关问题