- Home /
Drag and release mouse to Add forc to object's X and Y axis' only?
I've been stuck with this for a while. I've searched through the web but I can't seem to find anything related to it. I have a game object that can be pressed with the mouse/finger, when you do, you hold it and start dragging, upon release, the object will be shot towards the direction opposite of where your mouse was when releasing th drag. Considder it kind of a slingsshot effect without an actual slingshot.
My main concern as of now is what functions to use. Should I use onmousedown,onmousedrag and onmouseup or should i be using ondrag handlers?
Also, it is worth mentioning i'm not trying to make a beautiful angle, simply give the object force on it's Y and X axis' only. the gravity of the rigidbody will take care of the angle
Here's a visual example:
You could possibly store the position of where the mouseDown action happened, then store a second position where the mouseUp action happened. After you do that, calculate the angle those 2 points make relative to the horizontal plane.
Answer by hubi037 · Dec 06, 2015 at 02:41 PM
My suggestion would be to save the start position in your mouse down function and then compare it with the current position in your mouse up function. Simply calculate the vector between them like this:
Vector2 direction = startPosition - currentPosition;
You can also then get the length of that Vector with
float length = direction.magnitude
and use that length for your force calculations.
Answer by kidmosey · Dec 06, 2015 at 08:47 AM
Drag() is useful if you want to share this object with another, like dropping it onto that object.
If all you are doing is monitoring the pointer position, you can do so within the object as long as the mouse is down. So you can set a boolean on mouse down, monitor the mouse move events or draw a line in Update() if the boolean is true.
You will also receive a MouseUp() event even if the cursor is outside of the object, so long as the MouseDown() event was triggered inside that object.