- Home /
Make an object move to a given point by rotating to the correct direction first.
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.
Answer by Elysian.Zhen · Jan 16, 2012 at 12:05 PM
I got it. The trick is to round the values up if it is close to the target value. So for example, 4.143 will round up to 4. And 3.5697 will round up to 4 as well. This way my script won't cause random rotations because of the small values.
pos = transform.position;
pos = new Vector3(
Mathf.RoundToInt(pos.x) == (int) target.x ? Mathf.RoundToInt(pos.x) : pos.x,
1.5F,
Mathf.RoundToInt(pos.z) == (int) target.z ? Mathf.RoundToInt(pos.z) : pos.z
);
transform.position = pos;
Your answer
Follow this Question
Related Questions
Rotate an object around another object at an angle from the X axis? 1 Answer
Orienting multiple objects on the same line 1 Answer
Object not rotating when the associated trigger is triggered 1 Answer
Quaternion.FromToRotation misunderstanding 2 Answers
Controlling a rigged models muscle groups via script (C#) 0 Answers