Creating a set path for an object to move

I want to create a moving path for a gameobject that I control.

In the picture attached, I need the red square to be able to move around the blue rectangle on command.

What is the best approach to achieve this? I have read about creating nodes but I need the object to move smoothly around the rectangle based on what I press.

Thanks in advance

Won’t nodes solve that? A rectangle is just 4 points connected with lines between them, doesn’t matter how you represent it.

When you say “move smoothly around the rectangle”, what do you mean exactly and why do you believe nodes are not good enough of a solution?

1 Like

So I need to be able to control the object moving along the path. As in from node a to b, I need to be able to move them either towards node A or B but also be able to move back to the Node A or B on command before it has reached the next node.

You could use an AnimationCurve to lerp between two points of the rectangle, allowing you to define some custom movement-smoothing.
The curve could then be evaluated based on the percentage of the remaining distance to move between two points. You can accomplish that by comparing the distance between the two points with the current distance of the object moving towards the next point with Mathf.InverseLerp.

Pseudo-code (untested):

[Serializable]
public class Path {
   public Vector3 startPoint;
   public Vector3 endPoint;
   public AnimationCurve easing;

   public float DistanceBetweenPoints => (startPoint - endPoint).sqrMagnitude;
}
public class PathMover : MonoBehaviour {
   public Transform objectToMove;
   public float moveSpeed;
   public Path[] paths;

   private int currentPathIndex;
   private Path CurrentPath => paths[currentPathIndex];

   void Move() {
      float maxDistance = CurrentPath.DistanceBetweenPoints;
      float currentDistance = (objectToMove.position - CurrentPath.endPoint).sqrMagnitude;
      float percent = Mathf.InverseLerp(0f, maxDistance, currentDistance);

      float speed = Time.deltaTime * moveSpeed * CurrentPath.easing.Evaluate(percent);
      objectToMove.position = Vector3.MoveTowards(objectToMove.position, CurrentPath.endPoint, speed);

      //Just some value close enough to 1, since comparing floats using == is very unlikely to return true.
      if(percent >= 0.999) {
         //When percent reaches approximately 1, the end of the current path has been reached, and the next path should be started.
      }
   }
}