velocity stopper

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.

Sorry if im being a complete noob.

Cheers.

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.

–Eric

Ive just had a look at some of the script referncing, and realised that the OnMouseDown function is only applicable to a GUI Text, is this right?

If so, this is why its not working. I want my character (a ball) to stop moving when i just press the mouse down, and not over a gui.

Any ideas what function i need?

OnMouseDown also works on any object that has a collider component.

The best way to find out whether something is called in your script is to put some print statements. Like

function OnMouseDown() {
    print ("Stopping the rigidbody!"); 
    rigidbody.velocity = Vector3.zero; 
    rigidbody.angularVelocity = Vector3.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;
     } 
}

–Eric

Ah dude, thank you so much. It works like a treat. I’m well happy now.

Cheers.

if its any help this is a reset button for my physics based submarine shooter:

function FixedUpdate () {  
    	if(Input.GetKeyDown("r")){
    		rigidbody.freezeRotation = true;
        rigidbody.velocity.x=0;
        } 
}

function Update () 
{ 
	if(Input.GetKeyDown("r")){
transform.rotation.z = 0;
transform.rotation.x = 0;
 rigidbody.velocity.z = 0; 
 rigidbody.velocity.x = 0; 
  rigidbody.velocity.y = 0; 


}
if(Input.GetKeyUp("r")){
		rigidbody.freezeRotation = false;
}	

}

I know I doubled up a bit on the r key but hey, if it works, I can get on with something else…
Hope its useful.
AC