Can someone please explain the following code snippet to me ??
More specifically the creation of the right Vector
Vector3 forward = mainCam.transform.TransformDirection(Vector3.forward);//forward of camera to forward of world
forward.y = 0f;
forward = forward.normalized;
Vector3 right = new Vector3(forward.z, 0.0f, -forward.x);
Vector3 targetDirection = (horizontal * right + vertical * forward);
if (targetDirection.sqrMagnitude > 1f)
{
targetDirection = targetDirection.normalized;
}
//Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up) * camRotation;
Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up);
// Create a rotation that is an increment closer to the target rotation from the player's rotation.
Quaternion newRotation = Quaternion.Lerp(rigidbody.rotation, targetRotation, slerpDampTime * Time.deltaTime);
The target direction is the gamepad right stick input.
The script allows the gamepad to stay oriented with the rotation of the camera but I do not understand why the right vector was created this way ( - forward.x ??? )
I have tried to map it out pen paper and tracing source but it is not clicking
Thank you.
What would be an equivalent way to code this without using tricks? Can we use a cross product ? Why is this needed anyway? Just trying to understand completely but no matter thanks.
Its just to effectively rotate the forward vector by 90 degrees
You could go the hard way and create a 90 degree rotation around the up axis, and rotate the vector
Ot you could cross the forward vector with up
But why bother when you can just swap the x and z values. Its not a bad trick.
If we didn’t know the trick, we could draw a picture and “guess” the same formula from it:
Or we could solve it analytically:
which gives us two vectors (y, -x) and (-y, x) perpendicular to (x, y), one looks to the right and another to the left.
I personally would use my own helper methods that use cross product:
Vector3 right = Quaternion.Euler(0, 90, 0) * forward;
Vector3 targetDirection = (horizontal * right + vertical * forward);
Horizontal and vertical variables, I believe, are taken from the player’s input. The forward axis is taken from the camera and the right axis is calculated from it.
Actually, if the camera doesn’t roll, I think we could just take the right axis from the camera as well:
Vector3 right = mainCam.transform.right;
And even if it rolls, we could use the same trick as with the forward axis:
Vector3 right = mainCam.transform.right;
right.y = 0;
right.Normalize();