Rolling ball with Horizontal Input

Hi first time to the Unity forums. I was actually looking at a tutorial online and for the most part, I think I understand this code. Pretty much just rolling a ball around whenever I push a button. The only problem is that the ball keeps moving after I have let go of the button. It just keeps rolling and doesn’t stop. Can anyone help me with this? Also could someone give a brief explanation of this code, since I’m somewhat only assuming how it works?

 #pragma strict

 var rotationSpeed : int = 100; // 100 units per second 

 function Update () 
 {
    var rotation : float = Input.GetAxis ("Horizontal") * rotationSpeed;
	rotation *= Time.deltaTime; 
	rigidbody.AddRelativeTorque (Vector3.back * rotation);
 }

You are using a Rigidbody and the Physics engine to move the ball. In the absence of friction or drag, any force applied will last forever. Think shooting a rocket in space. After the engine quits, the rocket keeps going. In order to get the ball to slow down, you can do any of:

  1. Up the AngularDrag of the Rigidbody. It can be done in the Inspector, or it can be done in code.
  2. Direct manipulation of the AngularVelocity. This can be tricky.
  3. Add Physic materials to the colliders of the ball and to the surface the ball rolls on. These Physic materials define the amount of friction that occurs during collisions.

You can get a starter set of Physic materials:

Assets > Import Package > Physic Materials

There are a few other ways as well like adding a counter force to the rotation, or you can set the ‘isKinematic’ flag to true for an immediate stop.


The code above is adding torque (rotation force) to the ball. It uses the input from the “Horizontal” axis which can be tied to many things. Usually in the editor it is arrow or aswd keys, but it can use a joystick or mouse. The amount of rotation is scaled by Time.deltaTime to keep it consistent across varying frame rates and devices.