简体   繁体   中英

How to apply force on collision in iOS swift using sprite kit

I have something like so:

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
  }
}

Currently the user is able to drag the paddle with touch. It can only move horizontal. I'm not sure which property or how to determine how much force to apply to the ball based on the paddle's speed. Any advice on how to do this correctly?

I tried using paddle.velocity but those are just 0's

Am currently working on something similar myself. I have my own problems, but I kind of have it working. The way I've done this is by using the touches functions:

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);

}

If your collision func use something like:

ball.applyImpulse(self.vector);

Disclaimer: haven't tried to compile the above so might need tweaking for unwrapping of optionals, etc and obviously, YMMV.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM