Determine Direction of Movement based on Camera and Player Direction
I have a 3rd person camera that follows my player at an offset. For example (-10, 15 -10).
The player's movement can then be calculated based on the camera's offset.
Camera cam = Camera.main;
Vector3 forward = cam.transform.forward;
Vector3 right = cam.transform.right;
forward.y = 0f;
right.y = 0f;
forward.Normalize();
right.Normalize();
Vector3 direction = forward * Input.GetAxis("Vertical"); + right * Input.GetAxis("Horizontal");
Vector3 velocity = direction * speed * Time.deltaTime;
controller.Move( velocity );
LookAtMousePosition();
The player will also look towards where the mouse position via a ray cast.
private void LookAtMousePosition() {
Ray ray = Camera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hitInfo, maxDistance: 300f))
{
var target = hitInfo.point;
target.y = base.transform.position.y;
transform.LookAt(target);
}
}
Now I need to set an X and Z variable to determine animation to play in a 2d blend tree.
anim.SetFloat("walkX", someRandomX);
anim.SetFloat("walkZ", someRandomZ);
I think that I need to subtract the normalized direction the player is moving from the normalized direction the player is looking. But with all these different coordinate systems I am not able to figure out how to get the correct animation to play in the blend tree.
Anyone able to tell me how I should be thinking about the math here?
Answer by Stats · Jan 23, 2021 at 03:59 PM
I have resolved this by switching from using vectors to angles.
float angle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
float animAngle = (transform.eulerAngles.y - angle) + 90;