Dragging and launching an object.

Hi,

What I’m trying to achieve is for the player to be able to drag and release objects that are on the screen and upon release, they would move along the line they were getting dragged. One would call them “launch”-ing the objects.

Game is 2D and I can drag and move around objects so far, what I can’t seem to figure out is how to do the move-along-the-way-you-were-getting-dragged-at-upon-releasing-touch or launching it.

I Googled this around ofcourse but people were suggesting to use Rigidbody’s old demo that was in the Unity, not anymore apparently.

My objects have rigidbody component and I can use it.

What I’ve tried so far is to store last 100 position of the object while moving it around, then calculate average of those positions in order to get a vector3 that act as velocity vector of movement and then pass it to Rigidbody.addForce, but that doesn’t seem to work.

Any ideas?

Thanks.

I’m not sure of your game mechanic, but usually this kind of this is done using just a start and end point. So you get the position when the mouse or touch goes down, another position when the mouse or finger comes up then you get the vector by:

direction = endPos - startPos;

or if this is a slingshot:

direction = startPos - endPos;

The to your force will be something like:

rigidbody.AddForce(direction * forceFactor);

Note depending on your game mechanic, you may want to normalize the result. Without normalizing, the force added will be proportional to the distance of the drag.

I solved it robertbu’s approach but it was just took in the first and last position and is not very precise because when people touch and release, last few positions of touch can be faulty so I store last n positions of touch, then calculating vector between each two that are next to each other, then calculate average of those vectors and pass it to addForce.