[ C# ] Trying to slow down a rolling Sphere (or add friction ? )

Trying to slow down a sphere controlled by the player, when there is no input from axis.

2 checks are made

  • 1st is to check if the object is moving
  • 2nd is to check if the player is inputting to axis

without input i would like the sphere to stop, sooner than it would natually as if there is a high friction level.
But unfortunally i havent found any way to add friction so i guess adding a force in the oposite direction is the way to go.

Suggestions ?

	public float accelleration = 1;
	public float decelleration = 1.5f;
	public float newPos;
	public float lastPos;
	private float currentSpeed;
	private float opposingForce;

	void Update()
	{
		if (newPos != transform.position.x) 
		{
			//Player is moving
			//Debug.Log ("Moving ");
			
				//check if player has let go
				if(Input.GetAxis("Horizontal") == 0  Input.GetAxis("Vertical") == 0)
				{
					//Player is moving without imput
					//Debug.Log ("No touching");

					//slow down movement
					currentSpeed = rigidbody.velocity;
					opposingForce = -currentSpeed;

					rigidbody.AddRelativeForce(opposingForce * decelleration);

				}
		}
	}

You can adjust the physic material via code. Something like this:

PhysicMaterial mat;

void Start()
{
	mat = collider.sharedMaterial;
}
void IncreaseFriction () 
{
	mat.dynamicFriction += 0.1f;
}

More info on this page: Unity - Scripting API: PhysicMaterial

Nice, Thank you meta87.

Also found my deklarations was fubar…

Solved it by – removing the deklarations and changing line 21 through 25 to

rigidbody.AddRelativeForce(-rigidbody.velocity * decelleration);

Or you could set the angular drag and the drag. Think this is the best way if you want a natural movement and behavior.

If you like it to slowdown faster then just add the negative of the velocity vector. somthing like this.

Vector3 ourBackMovment = -rigidbody.velocity;
rigidbody.addRelativeForce(ourBackMovment);

have not tried this out but should make the ball stop quite fast.

Update

Now i feel stupid… Drag is what i was looking for…

1445063--77853--$pgCDzG1.png

No need for feeling stupid. The PhysX engine is quite complex. If you got other questions about the physics let me know maybe I can help I have some knowledge about PhysX, we used it in the game Switchball.

I was Fx programmer on that team but we all got involved in the Physics because it was under heavy development at the time we started to use it. (It was way before Nvidia bought the engine from Ageia who bought it from NovodeX in 2004, if I remember correctly). All the changes at that time made us to reballance and tweak the values over and over again. So the whole team got involved in that process.

1 Like