使用以下命令可以为您省去很多麻烦
myShip.physicsBody.applyImpluse(vector)。它的工作方式就像您
myShip在方向
vector点上施加了推力一样。如果您计算的
vector是从上次触摸位置到的x距离
myShip,则它会加速,减速,改变方向等。与您描述的方式非常接近,因为它只会在正确的方向上进行少量推动每个
update。
基本上,您存储了最后一次触摸的位置,然后在
update函数中计算了
CGVector从
myShip到的指向,
lastTouch并将其作为对物理身体的冲动。
就像是:
var lastTouch: CGPoint? = niloverride func touchesBegan(touches: NSSet, withEvent event: UIEvent) { let touch = touches.anyObject() as UITouch let touchLocation = touch.locationInNode(self) lastTouch = touchLocation}override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) { let touch = touches.anyObject() as UITouch let touchLocation = touch.locationInNode(self) lastTouch = touchLocation}// Be sure to clear lastTouch when touches end so that the impulses stop being appliesoverride func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) { lastTouch = nil}override func update(currentTime: CFTimeInterval) { // only add an impulse if there's a lastTouch stored if let touch = lastTouch { let impulseVector = CGVector(touch.x - myShip.position.x, 0) // If myShip starts moving too fast or too slow, you can multiply impulseVector by a constant or clamp its range myShip.physicsBody.applyImpluse(impulseVector) }}
您可能还想使用
linearDamping和的
angularDamping值
myShip.physicsBody。它们将帮助确定
myShip加速和减速的速度。
我最大化了
1.0我的应用程序中的值:
myShip.physicsBody.linearDamping = 1.0myShip.physicsBody.angularDamping = 1.0
如果
myShip不能足够快地停止,您还可以尝试对
update函数进行一些中断:
override func update(currentTime: CFTimeInterval) { // only add an impulse if there's a lastTouch stored if let touch = lastTouch { let impulseVector = CGVector(touch.x - myShip.position.x, 0) // If myShip starts moving too fast or too slow, you can multiply impulseVector by a constant or clamp its range myShip.physicsBody.applyImpluse(impulseVector) } else if !myShip.physicsBody.resting { // Adjust the -0.5 constant accordingly let impulseVector = CGVector(myShip.physicsBody.velocity.dx * -0.5, 0) myShip.physicsBody.applyImpulse(impulseVector) }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)