move but only in bounds

Hi there,

  • I have Obj_A, a Mesh Cube with Bounds bounds.
  • And in Obj_A, I have a child empty Transform tf_A.
  • Also in Scene, at another position, I have Transform tf_B.

What I want to do is move tf_A towards tf_B, but keep tf_A in the bounds of Obj_A.

If I have the line vector defined by the two points that tf_A and tf_B make, I know I can get any point on that line, but how do I limit it to stay within the bounds of Obj_A? **Keep in mind tf_B can move anywhere and tf_A has to keep up, but with in its Obj_A bounds.

Thanks

Doesn’t the MeshFilter have a min and max for bounds you could use?

Yes, but I am considering the vector, which could be anything…

I am not sure how I would cap (clamp), the Vector3 point, in the Bounds, when running a vector from Point A to Point B.

If you have a standard cube (obj_A), then you can try to constrain the child (tf_A) object to its local coordinates.

It’s like watching a fish in a home aquarium.

using UnityEngine;

public class Obj_A : MonoBehaviour
{
    public Transform tf_A;
    public Transform tf_B;

    public float Speed;

    void Update()
    {
        tf_A.position = Vector3.MoveTowards(tf_A.position, tf_B.position, Speed * Time.deltaTime);

        var halfBox = 0.5f;

        Vector3 nextLocalPos = tf_A.localPosition;
        nextLocalPos.x = Mathf.Clamp(nextLocalPos.x, -halfBox, halfBox);
        nextLocalPos.y = Mathf.Clamp(nextLocalPos.y, -halfBox, halfBox);
        nextLocalPos.z = Mathf.Clamp(nextLocalPos.z, -halfBox, halfBox);

        tf_A.localPosition = nextLocalPos;
    }
}

You can also change the position, size or rotation of the cube and it will still work.

2 Likes

thanks,
Willl try.

Solved… Unity has an internal Bounds Method, Bounds.ClosestPoint(Vector3 somePos);. It returns the closest point in the bounds, that somePos.

Nice!

https://docs.unity3d.com/ScriptReference/Bounds.ClosestPoint.html

1 Like

If your cube won’t rotate then this method is really good. But bounds is the volume that the object occupies in space. The image shows better how Bounds changes depending on the rotation of the object. The white frame is Bounds. The red dot is the closest point to tf_B .

There is also make raycast from tf_B in the direction of tf_A (which is inside the cube) and the point of contact of the beam will also be the border.

But if everything already works as expected, then you can leave your implementation.

1 Like

Good to know. Thanks for the visual.