Clamp when using MovePosition

I am moving a block back and forth along a single axis, it follows its target only while it is between two points.

 public GameObject Target;
    public float speed = 30f;

    public bool lockX = false;
    public bool lockY = false;
    public bool lockZ = false;

    public float bounds = 20f;

	void FixedUpdate () {
        Vector3 direction = (Target.transform.position - transform.position).normalized;
        direction.x = Mathf.Clamp(direction.x, -bounds, bounds);
        direction.y = Mathf.Clamp(direction.y, -bounds, bounds);
        direction.z = Mathf.Clamp(direction.z, -bounds, bounds);


        if (lockX)
        {
            direction.x = 0;
        }
        if (lockY)
        {
            direction.y = 0;
        }
        if (lockZ)
        {
            direction.z = 0;
        }

        rigidbody.MovePosition(transform.position + direction * speed * Time.deltaTime);
    }

What I want it to do is if it gets to the bounds, stop following in that direction. I have tried clamping to the bounds in each direction but the blocks keep following. I am pretty sure I need to clamp it some other way but not sure what the best way would be.

1 Answer

1

You are clamping the direction. From your description, you want to clamp the position. Something like:

public GameObject Target;
public float speed = 30f;

public bool lockX = false;
public bool lockY = false;
public bool lockZ = false;

public float bounds = 20f;

void FixedUpdate () {
	Vector3 direction = (Target.transform.position - transform.position).normalized;

	if (lockX)
	{
		direction.x = 0;
	}
	if (lockY)
	{
		direction.y = 0;
	}
	if (lockZ)
	{
		direction.z = 0;
	}

	var pos = transform.position + direction * speed * Time.deltaTime;

	pos.x = Mathf.Clamp(pos.x, -bounds, bounds);
	pos.y = Mathf.Clamp(pos.y, -bounds, bounds);
	pos.z = Mathf.Clamp(pos.z, -bounds, bounds);
	
	rigidbody.MovePosition(pos);
}

That fixed it! Thank you so much.