- Home /
Grab and throw object immediately
Hello everyone,
I would like that the player could grab an object and throw it using some force depending on the speed of the mouse and the angle/direction, I am using the script "DragRigidbody.js", it works well but there is an issue: The script makes sure to grab an object and can hold as long as the player would until it releases the right mouse button. What I would like is to only allow the player to catch an object and throw it immediately, for example grab it for 0.3 seconds, otherwise the object falls from his hands. Any help, please?
Thanks
Answer by robertbu · Feb 24, 2014 at 01:39 AM
You are going to need to modify the DragRigidbody.js script. Personally I'd make a new .js file...like MyDragRigidbody.js....and copy the contents to the file. I don't like multiple, different versions of standard scripts hanging around.
To make the changes you require, towards the top of the file (like 7 on my copy), put
private timestamp = 0.0;
Then on line 25 put:
timestamp = Time.time;
Finally modify line 61. Currently it will read:
while (Input.GetMouseButton (0))
And you want change it to:
while ((timestamp + 0.3 >= Time.time) && Input.GetMouseButton (0))
The 0.3 is the hold time you specified. The new condition to the while() loop compares the timestamp when the mouse button went down to the current time. If the current time is more than 0.3 ahead, it terminates the while() loop. This while() loop is doing the dragging.
Thanks robertu! However it doesn't works, I don't know why. It seems that the code timestamp = Time.time;
is not at the right place. Could you show me your complete code please?
I had the condition backwards in the last line. I fixed my answer. Here is an alternate that might be more understandable:
while (((Time.time - timestamp) < 0.3) && Input.Get$$anonymous$$ouseButton (0))