- Home /
Using a raycast's direction in parent's Y-rotation
Hi! I have a controllable character in 3d and I'm casting a raycast from it's center and for the direction of the raycast I'm using rigidbody.velocity.normalized. Now, with debug.drawRay I'm seeing that the raycast works properly, but I can't figure out how to get the rotation of the ray to use for the player's Y-rotation. The goal would be to detect the direction of the ray so that my character would have a target Y-rotation or something like that. Hope this question is simple enough. I didn't want to resort to UnityAnswers but here I am anyway.
Answer by robertbu · Oct 01, 2014 at 10:54 PM
The answer will depend on some context you did not provide:
Is the character always aligned with Vector3.up?
Is the velocity always parallel to the XY plane (i.e. no 'y' component)?
Did you construct your object so that the front is facing positive 'z' when the rotation is (0,0,0).
Do you need immediate rotation, or a smoothed rotation.
If you need a smoothed rotation, do you want that smoothing eased or at a constant speed?
If your answers are yes, yes, yes, no, no, then you can do this:
var v = rigidbody.velocity;
if (v != Vector3.zero) {
transform.rotation = Quaternion.LookRotation(v);
}
Other answers to the five questions will result in different code.
Hi, and thanks for the reply. I think that the character is always aligned with Vector3.up The second one is a no, the y-velocity comes from jumping & falling. Yes, it's facing positive z. And I was going for a smoothed rotation. I'm not too terribly much familiar with rotations, so could you enlighten me about "smoothing eased". To me it sound better than constant speed though. Cheers.
#pragma strict
var speed = 5.0;
function Update() {
var v = rigidbody.velocity;
v.y = 0;
if (v != Vector3.zero) {
var q = Quaternion.LookRotation(v);
transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * speed);
}
}
You may also like a constant speed rotation. Replace 'Slerp' with 'RotateTowards' and greatly increase the value of speed (in the Inspector).
Your answer
