How do I do movement clamps but with localPositions of an object?
hello, I'm trying to write a movement script where a cube moves around on a rotated 3D plane object but is constricted to that plane e.g. stays on the plane and stops at the edges of the plane. I've got this bit of movement code working that allows the cube to move around stuck on the plane, but it has no clamps to stop it when it gets to the edge.
public GameObject collisionsPlane;
Vector3 movement;
float horizontal;
float vertical;
public float speed = 2;
public float XSensitivity = 1;
public float ZSensitivity = 1;
public float MaxX = 5.1f;
public float MaxY = 5.1f;
public float MinX = -5.1f;
public float MinY = -5.1f;
private Vector3 heartPosition;
void Start()
{
heartPosition = collisionsPlane.transform.localPosition;
transform.position = heartPosition;
}
void Update()
{
if (Time.timeScale == 1)
{
horizontal = Input.GetAxis("Horizontal") * XSensitivity;
vertical = Input.GetAxis("Vertical") * ZSensitivity;
}
}
void FixedUpdate()
{
if (Time.timeScale == 1)
{
movement = new Vector3(horizontal, 0, vertical);
if (movement != Vector3.zero)
{
transform.localPosition += movement * Time.deltaTime * speed;
}
}
}
When I tried to change the code to create clamps I'm no longer able to keep the cube on the plane because I don't know how to clamp the Y position correctly. Here are the clamps I've made so far, which work on x and z but make the Y go off to a weird position:
void FixedUpdate()
{
if (Time.timeScale == 1)
{
movement = new Vector3(horizontal, 0, vertical);
if (movement != Vector3.zero)
{
heartPosition.x += horizontal;
heartPosition.z += vertical;
heartPosition.x = Mathf.Clamp(heartPosition.x, MinX, MaxX);
heartPosition.y = Mathf.Clamp(heartPosition.y; MinY, MaxY);
heartPosition.z = Mathf.Clamp(heartPosition.z, MinZ, MaxZ );
transform.localPosition = Vector2.Lerp(transform.localPosition, heartPosition, speed * Time.deltaTime);
}
}
}
How do I do clamps but with localPositions of an object?
Your answer
![](https://koobas.hobune.stream/wayback/20220613004135im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Space Shooter Tutorial, Player Movement and Boundaries 0 Answers
Limit object movement inside donut 0 Answers
Player teleport not working 0 Answers
How to move gameObject along a Vector3 with OnMouseDrag()? 0 Answers
Stop moving gameObject and push it back 0 Answers