How do you keep An object within a rectangle?

I literally have no code for this since I don’t know when to start, but I have this sprite that the player can move with their cursor, and I want to clamp it within a rectangle, I also don’t want to use any colliders.

  1. After the code handling your sprite’s movement, get its position as a variable
  2. Clamp the x component of the position to be between the rectangle’s left and right sides
  3. Clamp the y component of the position to be between the rectangle’s top and bottom sides
  4. Reassign your clamped position back as your sprite’s position. Vector3s are structs and cannot be changed in place so this use of a temporary variable is necessary

Mathf.Clamp is the function you can use to clamp a value between two other values. Clamp just says if your value is lower than the lower limit then return the lower limit, if it’s higher than the higher limit then return the higher limit, otherwise return it as is.

If you need more of a hand with how to implement this then let me know how you are representing your rectangle :slight_smile: