I am trying to implement GTA V style walking system, as in: When the character is facing the same direction as camera, and we press D, it first turns by quarter and if the key is kept pressed, character starts walking in right. Similarly if S is pressed, it turns half and starts walking back towards camera. And the animation played depends on current character position wrt camera, eg. if the character is facing right and A is pressed, it turns half left and then if kept pressed, starts walking.
I am trying to implement this in Unity. But I am having trouble finding the angle between camera and player in the Y plane. I tried using ProjectOnPlane function but I am getting all wrong angles. Here is my code for pressing of D key:
void Right()
{
Vector3 pVec = Vector3.ProjectOnPlane(transform.forward, Vector3.up);
Vector3 cVec = Vector3.ProjectOnPlane(mainCam.transform.forward, Vector3.up);
print(cVec);
float angle = Vector3.Angle(pVec, cVec);
print(angle);
if(angle >= 345 && angle <= 15)
{
animator.Play("StandQuarterTurnRight");
}
else if(angle >= 255 && angle <= 285)
{
animator.Play("StandHalfTurnRight");
}
else if(angle >= 165 && angle <= 195)
{
animator.Play("StandQuarterTurnLeft");
}
else if(angle >=75 && angle <= 105)
{
float forw = Input.GetAxis("Horizontal");
if (forw > 0.5f && !Input.GetKey(KeyCode.LeftShift)) forw = 0.5f;
else if (forw < -0.5f && !Input.GetKey(KeyCode.LeftShift)) forw = -0.5f;
animator.SetFloat("Speed", forw);
}
}
But I am getting wrong angles, I get 90 and nearby when my character is facing left as well as right side of the camera and I don’t get angles greater than 180. What am I doing wrong? Is there any better way to implement this?