Limiting movement

Hi,

I am trying to limit the movement of X-axis without luck.

Object movement is made this way:

float moveAmount = Input.GetAxis(“Mouse Y”) * MouseSensitivity;
transform.Translate(moveAmount, 0f, 0f);

I would like to do the limitation based on the localPosition. I have tried to clamp the position, but after I rotate the object the axis are not correct anymore and it doesn’t work.

I rotate the object like this:

transform.RotateAround(xformParent.position, Vector3.up, -Input.GetAxis(“Mouse X”) * MouseSensitivity);

I think i have to get the transform direction somehow and do the clamping with that, but not sure how to?

Assuming by X Axis you mean local forward?

transform.position += transform.forward * Input.GetAxis(...);

Thanks, but how do I implement the movement range into that?

You didn’t mention anything about “range” so I’m not sure what you’re referring to :slight_smile:

Maybe another idea would be to explain your goal and see if anyone can offer some ideas on how to achieve it :slight_smile: … From the top, I mean.

You have something you want to move left/right… you want it to rotate (does it have to be around something?), etc…

Ah, sorry :slight_smile: My goal is to limit the object movement in one axis. I have a parent object, let’s call it a PivotPoint and a child object Cue (billiard cue). I rotate the object around the pivot point and that works ok. Also the movement towards the pivot point works ok. But I want to limit the movement so it doesn’t go through the pivot point and no further than 0.5f in another direction.

So assuming what I posted before worked for what you wanted you could do something like this to clamp

transform.position += transform.forward * Input......

var toPoint = transform.position - pivot;
if (toPoint.magnitude > 0.5f)
{
    transform.position = pivot + toPoint.normalized * 0.5f;
}
1 Like

Thank you! I got it to work now. Your example worked fine, but I didn’t figure out how to clamp the position to the other direction. I tried this way, but when moving fast it started to bug because it went “through” the zero point and the magnitude started to increase again.

if (toPoint.magnitude < 0.1f)
{
    transform.position = transform.parent.position + toPoint.normalized * 0.1f;
}

I solved it by creating a variable for the cue position and clamping that:

cueDistance -= Input.GetAxis("Mouse Y") * (MouseSensitivity * Time.deltaTime * 0.05f);
cueDistance = Mathf.Clamp(cueDistance, 0.1f, 0.5f);

transform.localPosition = transform.forward * -cueDistance;
1 Like