- Home /
Rotate player (rigidbody) towards his movement
So I'm trying to make a rigidbody player to rotate towards where he's walking, but with no success.
I've got this code for movement relative to camera:
xAxis = Input.GetAxis("Horizontal");
zAxis = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(xAxis, 0, zAxis) * speed * Time.deltaTime;
movement = Camera.main.transform.TransformDirection(movement);
movement.y = 0;
rb.MovePosition(transform.position + movement);
.
and for the rotation I tried:
// this didn't work
transform.lookAt(movement)
//didn't work
transform.lookAt(transform.position + movement)
// didn't work
transform.rotation = Quaternion.LookRotation(rb.velocity, Vector3.up);
These not only don't work - they prevent me from walking at all.
Can someone help me on this please? Seems so simple, but I can't get it to work. Thanks
Answer by sparkzbarca · Jan 21, 2018 at 05:22 AM
Movement is a local postion, lookat takes a global
something like
transform.lookat(transform.position + movement) ;
should work, that'll convert your local into a global by factoring in your position is space.
Tried that too - same thing. It prevents me from moving and does not rotate in movement direction.
Answer by mpmlopes · Jan 21, 2018 at 08:18 AM
I’m having a similar problem, using a different approach (posted code here https://answers.unity.com/questions/1457622/update-heading-based-on-rotation.html ).
EDIT: Meanwhile, I’ve managed to figure it out. Note that my movement vector is fixed because I want my character to always move. If you want to control it, use the input vector. Here’s the code I ended up with:
void FixedUpdate () {
float moveHorizontal = Input.GetAxis("Horizontal");
movement.Set (1f, 0f, 0f);
movement = movement.normalized * speed * Time.deltaTime;
body.MovePosition (transform.position + (transform.forward * movement.x));
float turn = moveHorizontal * rotationFactor * Time.deltaTime;
Quaternion turnRotation = Quaternion.Euler (0f, turn, 0f);
body.MoveRotation (body.rotation * turnRotation);
}
Your answer
Follow this Question
Related Questions
Making my GambeObject rotate to face the direction of movement, smoothly. 0 Answers
calculating looking angle between 2 transforms 0 Answers
Flip over an object (smooth transition) 3 Answers
why can't my Rigidbody not rotate on slopes? 1 Answer
Limit Rotation of Rigidbody to 45 Degrees (Handlebars on a Bicycle) 1 Answer