# Make an object move to a given point by rotating to the correct direction first.

 0 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. more ▼ asked Jan 16 '12 at 11:33 AM Elysian.Zhen 118 ● 10 ● 11 ● 14 add new comment (comments are locked) 10|3000 characters needed characters left ▼ Viewable by all users

 0 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; `````` more ▼ answered Jan 16 '12 at 12:05 PM Elysian.Zhen 118 ● 10 ● 11 ● 14 add new comment (comments are locked) 10|3000 characters needed characters left ▼ Viewable by all users

By Email:

Topics:

x2166
x1367
x1278
x286
x195

asked: Jan 16 '12 at 11:33 AM

Seen: 546 times

Last Updated: Jan 16 '12 at 12:05 PM