Stopping Rigidbodies with Opposing Forces

Hi

I’m currently toying with Unity’s physics system and have been trying to use an opposing force to stop an object. I’m not that great at physics so let me know if I am doing it wrong. Here’s my code

function FixedUpdate()
{
    if(Input.GetButton("Stop"))
    {
        doStop();
    }
}

function doStop()
{
    var f:Vector3  = -(rigidbody.mass * rigidbody.velocity);
    rigidbody.AddForce(f, ForceMode.Impulse);
}

It seems to work to a limit so I think I am doing something right but the object moves in its original direction ever so slightly. Any thoughts to why this is happening?

You use ForceMode.Impulse so the effect will be immediately. If you relly want to stop it just zero the velocity :wink:

rigidbody.velocity = Vector3.zero;

Ok so I’ve solved the problem. I needed to treat gravity separately and apply a force opposite to gravity. Here’s the code. Hope it helps others.

function FixedUpdate()
{
	if(Input.GetButton("Stop"))
	{
		doStop();
	}
}

function doStop()
{
	var f:Vector3  = -(rigidbody.mass * rigidbody.velocity);
	rigidbody.AddForce(f, ForceMode.Impulse);
	rigidbody.AddForce(-(Physics.gravity), ForceMode.Acceleration);
}

Thought I would rephrase my solution because some might get confused why I didn’t just set rigidbody.useGravity = false;. I avoided this so I could use damping on the effect like so

private var strength:float = 0;
private var smoothTime:float = 2.0;

    function FixedUpdate()
    {
    	if(Input.GetButton("Stop"))
    	{
    		doStop();
    	}
    	if(Input.GetButtonUp("Stop"))
    	{
    		strength = 0;
    	}
    }
    
    function doStop()
    {
    	Mathf.SmoothDamp(0.0f, 1.0f, strength, smoothTime);
    	var f:Vector3  = -(rigidbody.mass * rigidbody.velocity) * strength;
    	rigidbody.AddForce(f, ForceMode.Impulse);
    	rigidbody.AddForce(-(Physics.gravity) * strength, ForceMode.Acceleration);
    }

rigidbody.velocity is accidentally the right value (since force is mass x acceleration, and you want to accelerate to a zero velocity). I think imperfection in floating point math will result in some residual movement. I think you’ll need to add a script that’ll dampen / eliminate the resulting movement. So anything in your system traveling slower than some “minimum” speed will stop.