Throw an object on collision with mouse cursor

Hi all,

I hope the header isn’t too confusing, it’s difficult to describe such matter in such short length :slight_smile:

Anyhow, what I want to do is not supposed to be too difficult.

I got a scene where my camera is above a table and it is pointing towards the table from above, so the camera is actually showing a top view of the table.

On the table I have a ball laying still.

I need to allow the user to hit the ball while gaining momentum from one of the sides surrounding the ball, that way the ball would fly to the opposite direction.

For example as shown below -

  1. The user holds down the mouse on the right side of the table, far from the ball.
  2. The user moves the mouse cursor while still holding the mouse button towards the ball
  3. The ball collides with the mouse cursor, and depending on how “hard” it was hit, it should move to the other side faster/slower.

alt text

One thing to keep in mind - I need a method that will not be hard to port to Android/iOS touch interface in the future.

Thanks!!

The way I would do this, would be to have an empty object which gets moved to the mouse position (using some combination of screenPointToRay and Physics.Raycast) every frame. In this object, I would keep a Vector3 variable which saves the position from the last frame (resets every time) and then use Physics.Linecast to determine ‘collisions’.

To determine the speed, it’s a simple as working out the instantaneous velocity of the object every frame, something like this-

Vector3 velocity = (transform.position - lastPosition) / Time.deltaTime;

Then I would use a rigidbody on the ball, and then inside the Linecast function, I would do something like this-

hit.rigidbody.AddForceAtPosition(velocity * someConstant, hit.point, ForceMode.Impulse);