# How can i clamp X velocity?

I am trying to prevent my cube from side left to right by clamping its local X sideways velocity but the script that I’m using is only clamping its global y velocity, can anyone help me try fixing this i just can’t seem to figure it out, thanks

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {

``````Rigidbody rb;
public float maxSideSpeed;
public float moveSpeed;
public float turnSpeed;

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

void Update()
{

Vector3 clampVel = rb.velocity;

clampVel.x = Mathf.Clamp(clampVel.z *maxSideSpeed , 0, 0);

rb.velocity = clampVel;

rb.AddForce (transform.forward * Input.GetAxis("Vertical") * moveSpeed * 10000 * Time.deltaTime);

transform.Rotate (Vector3.up, Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime);

}
``````

}

Hi,
I don’t use rigid bodies much but did stumble over the below

Not sure it helps but hope it does,
Good luck

Assuming the Cube is moving on a plane where left and right are on the X axis and up and down are on the Z axis, Define the following float which will represent the how fast you want to allow the object to go in each direction:

``````private float maxVelocityX = 5f;
private float maxVelocityZ = 5f;
private float minVelocityX = -5f;
private float minVelocityZ = -5f;
``````

The add the following method in Update()

``````void CheckVelocity()
{
if(mybody.velocity.x > maxVelocityX)
{
mybody.velocity = new Vector3(maxVelocityX, 0, mybody.velocity.z);
}
if(mybody.velocity.z > maxVelocityZ)
{
mybody.velocity = new Vector3(mybody.velocity.x, 0, maxVelocityZ);
}

if(mybody.velocity.x < minVelocityX)
{
mybody.velocity = new Vector3(minVelocityX, 0, mybody.velocity.z);
}
if(mybody.velocity.z < minVelocityZ)
{
mybody.velocity = new Vector3(mybody.velocity.x, 0, minVelocityZ);
}
}
``````