- Home /
how to make an object move in a rectangle path ?
hi, im trying to develop a script for an obstacle to make it auto move in a rectangle path. at first the object starts moving from right to left , then it goes up , and when it has to go from left to right it becomes fixed on its place and starts shaking . i tried to fix the problem but no chance ... this is the script and i hope someone can help me :
private void Update()
{
if(transform.position.x >= -1f)
{
Vector3 horizontal = new Vector3(-1f, 0f, 0f);
transform.position = transform.position + horizontal * Time.deltaTime;
return;
}
else if ( transform.position.y <= 1f)
{
Vector3 horizontal = new Vector3(0f, 1f, 0f);
transform.position = transform.position + horizontal * Time.deltaTime;
return;
}
else if(transform.position.x <= 1f && transform.position.x <= -1f)
{
Vector3 horizontal1 = new Vector3(1f, 0f, 0f);
transform.position = transform.position + horizontal1 * Time.deltaTime;
return;
}
if (transform.position.x <= 1f)
{
Vector3 horizontal = new Vector3(-1f, 0f, 0f);
transform.position = transform.position + horizontal * Time.deltaTime;
return;
}
}
Answer by FlaSh-G · Aug 11, 2020 at 08:43 PM
Don't try to write complex if statements to check where on the rectangle the object currently is. Instead, have a piece of data that just remembers it.
public Vector2[] points; // In the editor, put your rectangle coordinates in here
private int nextPointIndex = 0;
private void Update()
{
var reachedNextPoint = transform.position == points[nextPointIndex];
if (reachedNextPoint)
{
nextPointIndex++;
if (nextPointIndex >= points.Length)
{
nextPointIndex = 0;
}
}
transform.position = Vector3.MoveTowards(transform.position, points[nextPointIndex], speed * Time.deltaTime);
}
The nextPointIndex
variable will always store the index of the point we're currently moving towards. Once we reach point 0, it goes up to 1 and we move towards point 1. Once the last point in the points
array is reached, it goes back to 0. That entire part...
nextPointIndex++;
if (nextPointIndex >= points.Length)
{
nextPointIndex = 0;
}
...can be shortened to...
nextPointIndex = (nextPointIndex + 1) % points.Length;
...but I've written it out for the sake of clarity.
Your answer
![](https://koobas.hobune.stream/wayback/20220613005343im_/https://answers.unity.com/themes/thub/images/avi.jpg)