How do I make an object move to a given point by first rotating itself to the correct direction then move forward? BUT I don’t want diagonal movements, therefore first move the x value of the position until it is the same with the target’s x value. Then repeat for z as well.
For example, my character is standing at (0,0) and facing in the forward direction (0,0,1).
I want him to move to (15,21). So I will first rotate him 90 degrees so he can move forward in the x axis. I’ll keep him moving forward in the x axis until it is 15. Next, I’ll rotate him -90 degrees so he is now facing in the z axis direction. And I’ll keep moving him forward in the z axis until it is 21. Finally, stopping on the spot.
Here’s my code (Which apparently doesn’t work):
var pos = transform.position;
//pos = new Vector3((float) Mathf.Round(pos.x), (float) Mathf.Round(pos.y), (float) Mathf.Round(pos.z));
pPos = pos;
if (target == Vector3.zero || target - pos == Vector3.zero)
return;
Debug.Log(string.Format("Pass! Target: {0} Pos: {1}", target, transform.position));
var angle = 0F;
if (target.z != pos.z)
{
if (target.z > pos.z)
{
angle = Mathf.PI;
}
else if (target.z < pos.z)
{
angle = 0F;
}
}
else if (target.x != pos.x)
{
if (target.x > pos.x)
{
angle = Mathf.PI/2;
}
else if (target.x < pos.x)
{
angle = Mathf.PI*3/2;
}
}
if (Mathf.Abs(angle - currRot) > float.Epsilon)
{
var diff = angle - currRot;
transform.RotateAround(Vector3.up, diff);
currRot = angle;
}
transform.position = (transform.forward) + pos;
Would anyone be kind enough to help me here? Thanks.