- Home /
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);
}
Answer by robertbu · May 01, 2014 at 11:12 PM
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:
Up the AngularDrag of the Rigidbody. It can be done in the Inspector, or it can be done in code.
Direct manipulation of the AngularVelocity. This can be tricky.
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.
thank you! great answer. this makes much more sense now
Your answer
![](https://koobas.hobune.stream/wayback/20220613144038im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Combining 2 Vectors for Diagonal Movement 1 Answer
How can I make my character jump & move him by zone 0 Answers
Rotation too complicated 3 Answers
how can i instantly change the the direction of a force and speed aplyd to a 2D object 1 Answer
How to drag and move a character left and right using touch controls in an endless runner game? 0 Answers