- Home /
Auto-moving RigidBody2D to a point, using thrusters (part of AI)
I wrote a coroutine, which is part of AI and it is meant to auto-drive the object to a point in 2D space, using left, right, up and down thrusters:
IEnumerator ReturnToPoint(Vector2 posVec)
{
moveHorizontal = true;
moveVertical = true;
if(transform.position.x >= posVec.x && transform.position.y >= posVec.y)
{
while(transform.position.x >= posVec.x || transform.position.y >= posVec.y)
{
if (transform.position.x >= posVec.x)
{
thrustLeft = true;
}
else
{
thrustLeft = false;
rig.velocity = new Vector2(0.0f, rig.velocity.y);
}
if(transform.position.y >= posVec.y)
{
thrustDown = true;
}
else
{
thrustDown = false;
rig.velocity = new Vector2(rig.velocity.x, 0.0f);
}
yield return 0;
}
}
else if(transform.position.x >= posVec.x && transform.position.y <= posVec.y)
{
while(transform.position.x >= posVec.x || transform.position.y <= posVec.y)
{
if(transform.position.x >= posVec.x)
{
thrustLeft = true;
}
else
{
thrustLeft = false;
rig.velocity = new Vector2(0.0f, rig.velocity.y);
}
if(transform.position.y <= posVec.y)
{
thrustUp = true;
}
else
{
thrustUp = false;
rig.velocity = new Vector2(rig.velocity.x, 0.0f);
}
yield return 0;
}
}
else if(transform.position.x <= posVec.x && transform.position.y >= posVec.y)
{
while(transform.position.x <= posVec.x || transform.position.y >= posVec.y)
{
if(transform.position.x <= posVec.x)
{
thrustRight = true;
}
else
{
thrustRight = false;
rig.velocity = new Vector2(0.0f, rig.velocity.y);
}
if(transform.position.y >= posVec.y)
{
thrustDown = true;
}
else
{
thrustDown = false;
rig.velocity = new Vector2(rig.velocity.x, 0.0f);
}
yield return 0;
}
}
else if(transform.position.x <= posVec.x && transform.position.y <= posVec.y)
{
while(transform.position.x <= posVec.x || transform.position.y <= posVec.y)
{
if(transform.position.x <= posVec.x)
{
thrustRight = true;
}
else
{
thrustRight = false;
rig.velocity = new Vector2(0.0f, rig.velocity.y);
}
if(transform.position.y <= posVec.y)
{
thrustUp = true;
}
else
{
thrustUp = false;
rig.velocity = new Vector2(rig.velocity.x, 0.0f);
}
yield return 0;
}
}
moveHorizontal = false;
moveVertical = false;
thrustRight = false;
thrustLeft = false;
thrustDown = false;
thrustUp = false;
}
It appears to work fine, however...
Is there a better way to write this coroutine? For example, by using Vector2.MoveTowards
or something else? I ask this because, I suspect that there is a better way and I could pick quite a few tricks and tips about general Vector manipulation, by knowing it.
Comment
Your answer
Follow this Question
Related Questions
Enemy Rigidbody Not Responding to Gravity 1 Answer
How do I make this kind of follow script? 1 Answer
FPS RIGIDBODY PROBLEM 1 Answer
AI follow and crash into Player 0 Answers
Detecting the right time to play a landing animation? 1 Answer