# Keep constant velocity

Hi, I’m one of the many Unity newbies who’s making a Breakout-ish game for learning purposes. I use physics for moving the ball and have physics materials with 1 bounciness and 0 friction on all the objects. Problem is that sometimes the ball looses its velocity. This usually happens when the ball gets squeezed between the paddle and the wall or in between two close bricks.

Have I overlooked anything or is there a way to force the ball to have a constant velocity? Best of all would be to have a script variable that allows me to increase or decrease the speed in-game.

I’ve looked into scripting the movement instead of using physics, but the math is way beyond my understanding

1 Like

There are two ways to maintain a constant velocity on an object (that are easy that I know about)

• If you are using a rigidbody, then inside of LateUpdate and/or Update simply set

rigidbody.velocity = constantVelocity;

• If you are not using a rigidbody, or if you want there to be no way to interact with the object via physics, then simply do this in LateUpdate or Update:

transform.position += constantVelocity * Time.deltaTime;

where `constantVelocity` is a Vector3 containing the desired change in position per second

Another way to solve your problem is the constant force component

I’m not sure how to use this solution when using physics for the movement and bounces though. If I have a [10,10,0] constant velocity the ball will just move up to the right until it hits a rigidbody and gets stuck in a corner or something. It won’t bounce around at a set speed.

``````public class Ball : MonoBehaviour
{
float constantSpeed = 10f;
public Rigidbody2D rb;

void Start ()
{
Rigidbody2D rb = GetComponent<Rigidbody2D>();
}

void Update ()
{
rb.velocity = constantSpeed * (rb.velocity.normalized);
}
}
``````

it works like a charm so far. I can quickly adjust the variable to control balls speed this way. Just remember to drag in the Unity RigidBody2D component from your ball into the scripts slot. If someone know how to asign it within the script share the wisdom, but draging works just fine.
Thanks.