# Is there a way to lock velocity?

Im making a 2d pong like game with powerups. one of the powerups doubles the velocity of the ball. Ive been having problems with the physics engine as when I hit the ball with the side of my paddle the ball speeds up alot. Is there any way to lock the velocity to a certain number unless the powerup is activated?`public Rigidbody2D rb;
public float ballForce;
public Rigidbody2D powerUpRB;
private bool timerStart = false;
private float timeLeft = 1f;

``````// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update()
{

if (Input.GetKeyUp(KeyCode.Space))
{
rb.velocity = new Vector2(ballForce, ballForce);
}
}

void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.name != "doubleBallSpeed") return;

rb.velocity = new Vector2(ballForce * 2, ballForce * 2);
StartCoroutine("DelayTime");
Destroy(coll.gameObject);
}

IEnumerator DelayTime()
{
yield return new WaitForSeconds(5f);
rb.velocity = new Vector2(ballForce / -2, ballForce / 2);
}
``````

}

Yes, there is. What you need to do is measure the Magnitude of the velocity. If it exceed the max speed, then you normalize the vector and multiply it by the max speed.

``````     Vector2 vel = new Vector2();
float mag = vel.magnitude;
if (mag >= MaxSpeed)
{
vel = vel.normalized * MaxSpeed;
}
``````

I recommend you try Mathf.Clamp(float value, float min, float max). It returns max if value is greater than max.

Example:

``````float xVel = Mathf.clamp(ballForce * 2, minVel, maxVel);
float yVel = Mathf.clamp(ballForce * 2, minVel, maxVel);
rb.velocity = new Vector2(xVel, yVel);
``````

I am not sure what you mean by “lock the velocity to a certain number”. If you want the velocity would not exceed some limits, you can use Mathf.Clamp. Or if you want to keep the speed the same all the time, then you just use Update function and assign there constant velocity.