Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Moving with Velocity and Clamp an Axis

Discussion in '2D' started by SheldonS, Sep 23, 2019.

  1. SheldonS

    SheldonS

    Joined:
    Jul 23, 2015
    Posts:
    21
    Hello everyone,

    I am a bit stuck. I move an object using Velocity on the rigid body.
    Code (CSharp):
    1. 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?
     
  2. SheldonS

    SheldonS

    Joined:
    Jul 23, 2015
    Posts:
    21
    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.

    Code (CSharp):
    1. transform.position = new Vector2(Mathf.Clamp(transform.position.x, fieldLeftLimit, fieldRightLimit), Mathf.Clamp(transform.position.y, fieldBottomLimit, fieldTopLimit));
     
  3. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,557
    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.
     
    Pilofan and SheldonS like this.
  4. SheldonS

    SheldonS

    Joined:
    Jul 23, 2015
    Posts:
    21
    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!