- Home /
Rotate object to face direction of movement
Hi, I have a rigidbody which I am moving around in a 2D way using the following code:
void FixedUpdate() {
float xPos = Input.GetAxis("Horizontal") * _player.playerSpeed * Time.deltaTime;
float yPos = Input.GetAxis("Vertical") * _player.playerSpeed * Time.deltaTime;
Vector3 newPos = new Vector3(xPos, 0, yPos);
_position = _position + newPos;
if(_position != Vector3.zero)
{
_player.rigidbody.MovePosition(_position);
}
}
It's working fine, but I'm struggling to make it so the gameObject rotates to face the direction in which the object is moving. Most of the code I have found assumes we are wanting to move X, Y and Z where as I am only really interested in X and Z.
If anyone has anyone suggests as to how I can get this functionality I'd be very grateful :)
Answer by gl03 · May 28, 2012 at 08:54 PM
You can simply set the object's blue axis to the rigidbody's velocity Vector3:
transform.up = rigidbody.velocity;
If you want to use a rigbody...
Answer by qJake · May 06, 2010 at 09:05 PM
Could you use Transform.LookAt, and then just lock the Y-axis to whatever you need it to be?
Answer by sean · May 06, 2010 at 09:08 PM
Sorry I can't provide a code sample, I'm still in the "trial-and-error the syntax as I go" stage of Unity-specific javascript, but the theory is basically take the direction you're moving, either pulled from the .x and .z of your velocity or tracked frame to frame as a difference of previously-saved and current x & z position and drop it in a vector. I believe Unity has some LookAt or set-rotation-to-face-vector functions built in, otherwise you're back to using a Mathf.atan2 call and euler rotations.
But Spike's probably got the straightforward built-in: .LookAt where you're going, and then set the pitch component of the object rotation to 0.
Answer by anivader1789 · Jan 19, 2014 at 03:53 AM
See the top voted answer in this thread
http://answers.unity3d.com/questions/33380/rotate-to-facing-direction.html
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Unity3D Ai wont shoot 1 Answer
Trouble with OnCollisionEnter and Exit 1 Answer
hit.normal cube 0 Answers
How to keep rotation from switching between - and + after a 360? 0 Answers