Moving with Velocity and Clamp an Axis

Hello everyone,

I am a bit stuck. I move an object using Velocity on the rigid body.

myRigidBody.velocity = aiVector * AIMovementSpeed;

The aiVector is a Vector2 that I set the axis. Since this is called in fixed update I use a small value for the direction I want it to move.

The AIMovementSpeed is a float.

This works great but I want to limit the X or Y that the object can move. I do not want to use a trigger or collider, I have those and they serve another purpose. Although I have seriously been rethinking it.

Is there a way to move an object with the velocity but clamp its X or Y value between a min and max?

I do not know if it is the best way, but I did it in the fixed update after I call my function to move the object.

transform.position = new Vector2(Mathf.Clamp(transform.position.x, fieldLeftLimit, fieldRightLimit), Mathf.Clamp(transform.position.y, fieldBottomLimit, fieldTopLimit));

Don’t ever change the Transform on a GameObject with physics objects. Use Rigidbody2D.MovePosition instead and check Rigidbody2D.position for clamping.

The message here being that adding a Rigidbody(2D) to a GameObject means you’re giving it control of the Transform so you shouldn’t touch it. You should use it as a proxy and always go via its API.

Hope that helps.

2 Likes

I’m sorry I forgot to come back and update. Changing my player to move with this had no noticeable change. Changing the AI did have a noticeable change. The AI moves much more smoothly and natural.

Thank you very much!