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 $$anonymous$$ · Aug 11, 2020 at 06:35 PM
You probably want to use animations for this one, check out Jason Weimann he made a video on 'moving in unity'.
Animations can be done without the need to write code, and can interact with the physics system, so no drawbacks for this case.
.
The problem with your code is that some of these can be true at the same time, so your object try to move in different direction at the same time resulting in flickering.
.
You need to define some kind of state for what direction it is moving
.
if(transform.position.x <= 1f && transform.position.x <= -1f)
This here doesn't make sense,
if x is less than -1 it will always be less than +1
first thank you for your help. i tried animations for the first time but the problem is that i have many objects with the same path and the delay between these objects is not stable (most of the time they collide on each other) and i didn't find a solution for that .
Your answer
Follow this Question
Related Questions
Transform.position and transform.localPosition don't work on my game object 0 Answers
I want to spawn objects probabilistically. 0 Answers
How do you pick up an instantiated object? 1 Answer
Hey Guys How to make a script 'private Transform Waypoint;, 0 Answers
How can I move an object between two positions, while it is on a rotating platform? 0 Answers