如何使用精灵套件在iOS swift中对碰撞施加力

时间:2014-09-20 04:05:16

标签: ios swift sprite-kit game-physics

我有类似的东西:

func didBeginContact(contact: SKPhysicsContact) {
  var paddle = getPaddleFromContact(contact) //of type SKPhysicsBody
  var ball = getBallFromContact(contact) //of type SKPhysicsBody
  if(paddle != nil && ball != nil){
   //apply force to ball depending on the speed/velocity of the paddle 
   //NEED HELP WITH THIS LOGIC
  }
}

目前,用户可以通过触摸拖动球拍。它只能水平移动。我不确定哪种属性或如何根据球拍的速度确定施加到球上的力量。关于如何正确地做到这一点的任何建议?

我尝试使用paddle.velocity,但那些只是0&#39>

1 个答案:

答案 0 :(得分:0)

我目前正在做类似的事情。我有自己的问题,但我有点工作。我这样做的方法是使用touches函数:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

   let touch = touches.anyObject() as UITouch!;
   self.firstLocation = touch.locationInNode(self);

}

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {

   if (nil == self.firstLocation) {
       // this is reset to nil in your collision function
       return;
   }

   let touch = touches.anyObject() as UITouch!;
   let location = touch.locationInNode(self);

   // use this vector in your collision function
   self.vector = CGVectorMake(self.firstLocation.x - location.x, self.firstLocation.y - location.y);

}

如果你的碰撞功能使用类似的东西:

ball.applyImpulse(self.vector);

免责声明:没有尝试编译以上所以可能需要调整以解包可选项等,显然,YMMV。