更新:我已解决问题,并找到了比提供的答案更简化的方法。我的解决方案是让宇宙飞船的速度等于它距离我的手指触摸的距离。对于更快的移动,您可以将此速度乘以一个常数。在这种情况下,我使用了16。我还取消了在touchesEnd事件中将lastTouch设置为nil的设置。这样,即使我松开手指,飞船仍会停止。
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if let touch = lastTouch {
myShip.physicsBody.velocity = CGVector(dx: (lastTouch!.x - myShip.position.x) * 16, dy: 0)
}
}
我有一个 SPACESHIP 节点,只能在 X 轴上移动。当用户在屏幕上按下并保持时,我希望 SPACESHIP 能够移动到手指的 x 坐标,并且直到手指松开为止不停止向手指移动。如果 SPACESHIP 靠近用户的手指且用户的手指仍然按下,我希望它逐渐减速并停止。我还希望在 SPACESHIP 改变方向、启动和停止时应用这种平滑运动。
我正在尝试找出最好的方法来实现这一点。
到目前为止,我已经创建了节点并使其正确移动,但存在一个问题:如果我按住屏幕并保持,飞船最终将越过我的手指并继续移动。这是因为改变飞船方向的逻辑仅在我移动手指时触发。因此,将手指移到飞船上以改变飞船方向有效,但如果飞船越过我的静止手指,则不会改变方向。
我需要 SPACESHIP 节点识别出它何时越过了我的静态手指,并根据其接近程度改变方向或停止。
以下是相关代码:
第一部分:当用户按下时,找出触摸的位置并使用速度相应地移动我的飞船 (SPACESHIP)。
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
let touch = touches.anyObject() as UITouch
let touchLocation = touch.locationInNode(self)
if (touchLocation.x < myShip.position.x) {
myShip.xVelocity = -200
} else {
myShip.xVelocity = 200
}
}
第二部分 当用户移动手指时,触发一个事件来检查手指是否已经移动到了船的另一侧。如果是,改变船的方向。
override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {
let touch = touches.anyObject() as UITouch
let touchLocation = touch.locationInNode(self)
//distanceToShip value will eventually be used to figure out when to stop the ship
let xDist: CGFloat = (touchLocation.x - myShip.position.x)
let yDist: CGFloat = (touchLocation.y - myShip.position.y)
let distanceToShip: CGFloat = sqrt((xDist * xDist) + (yDist * yDist))
if (myShip.position.x < touchLocation.x) && (shipLeft == false) {
shipLeft = true
myShip.xVelocity = 200
}
if (myShip.position.x > touchLocation.x) && (shipLeft == true) {
shipLeft = false
myShip.xVelocity = -200
}
}
第三部分 当用户从屏幕上松开手指时,我希望飞船停止移动。
override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
myShip.xVelocity = 0
}
第四部分:更新改变船只位置的事件。
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
let rate: CGFloat = 0.5; //Controls rate of motion. 1.0 instantaneous, 0.0 none.
let relativeVelocity: CGVector = CGVector(dx:myShip.xVelocity - myShip.physicsBody.velocity.dx, dy:0);
myShip.physicsBody.velocity = CGVector(dx:myShip.physicsBody.velocity.dx + relativeVelocity.dx*rate, dy:0);
感谢阅读,期待回复!