Search code examples
iosswiftsprite-kitskphysicsbodyskshapenode

Best way to perform a touch moved hit with a SKShapeNode like with a baseball bat?


I want to hit a ball with a baseball bat which moves with the users finger movement.

I tried the following two methods:

(Bat = SKShapeNode(...))

1. - Use of didBeginContact and then applying the Velocity to the ball from the last touchesMoved

Bat.position = location
CGVectorMake(-((touch.previousLocationInNode(self).x-location.x)*30), -((touch.previousLocationInNode(self).y-location.y)*30))
body.velocity = vectorPower
(tried with .applyImpulse() aswell)

The Problem here is, that it looks unreal and doesn't work all the time and you have to tweak the values to get a remotely good solution. Also because the Bat is rotated this solution could not work right.

2. - Use SKPhysicsBody to physically bump both objects together

Ball.physicsBody?.restitution = 1
Bat.physicsBody = SKPhysicsBody(rectangleOfSize: ..)
...
Bat.position = location

The problem here is, that there is no real velocity of the player movement and the baseball bat sometimes just go through the ball without hitting it.

I now wonder if there is a best practice to perform the user based collision with the right bouncing based on the players movement speed?

Thanks in advance! Any help would help a lot.


Solution

  • If someone is having this question too - i solved it myself:

    1. Calculate the velocity from your movement

    2. Apply this velocity to your node at all times you move

    3. Disbale the velocity by reseting the position at every update

    This way, even if you move the node, it bumps other nodes with the right velocity.