Hello all, im trying to get an object to stop moving by pressing the mouse button. Basicaaly bringing to a complete stop when pressed, at the moment i have this code on the object:
function OnMouseDown(){
rigidbody.velocity = Vector3.zero;
rigidbody.angularVelocity = Vector3.zero;
}
There doesn’t seem to be any problem with the code apart from it not doing anything.
That will work, but only for that one frame when you click on it. If there are still any forces acting on it (like gravity), it will start moving again the next frame. I’m not sure what your situation is, but you could try adding this:
rigidbody.isKinematic = true;
And then change isKinematic to false when you want it to move again. But that’s not necessarily appropriate, since it stops the physics engine from working on the object. If you can’t use the isKinematic method, you have to make sure the object isn’t being affected by anything else after you set the velocity to zero.
Ah yes it does stop the object from moving. But i cant have it only stopping the object when clicking on it, it needs to do it wherever the cursor is. Any chance of this happening?
In other words, you want it to stop if the player just clicks anywhere? If that’s the case, check for a mouse click in an Update function instead. Actually FixedUpdate would probably be more appropriate since we’re dealing with phyics.
function FixedUpdate() {
if (Input.GetMouseButtonDown(0) ) {
rigidbody.velocity = Vector3.zero;
rigidbody.angularVelocity = Vector3.zero;
}
}