The following code supposes to move and rotate the character based on the plyer's input. However, it works perfectly when moving forward, left, and right, but keeps spinning when moving backward.
Does anyone know why that is? I really can't figure out how is that possible, it uses exactly the same code with moving toward other directions, why it just doesn't work when it comes to moving backward?!
Please help me! I'm losing my sanity over this.
The code is placed inside Update() function.
PS: So, now I am certain the problem is that the if statement for moving backward is always triggered. I logged transform.foward when moving backward, it outputs (0,0,-1) but the Equals function still returns false. I don't understand why is that, and why this does not happen to any other directions. Please help, thank you!
PSS: So I switched .Equals function to == operation, and it works now. Still curious about why this happens though.
// Player Movements
hInput = Input.GetAxis("Horizontal");
vInput = Input.GetAxis("Vertical");
if(Mathf.Abs(hInput) > Mathf.Abs(vInput))
{
if(hInput > 0)
{
// move right
if (!transform.forward.Equals(new Vector3(1, 0, 0)))
{
transform.Rotate(90, 0, 0);
}
} else if(hInput < 0)
{
// move left
if (!transform.forward.Equals(new Vector3(-1, 0, 0)))
{
transform.Rotate(-90, 0, 0);
}
}
controller.Move(new Vector3(hInput, 0, 0) * mSpeed * Time.deltaTime);
} else if(Mathf.Abs(hInput) < Mathf.Abs(vInput))
{
if (vInput > 0)
{
// move forward
if (!transform.forward.Equals(new Vector3(0, 0, 1)))
{
transform.Rotate(90, 0, 0);
}
}
else if (vInput < 0)
{
// move backward
if (!transform.forward.Equals(new Vector3(0, 0, -1)))
{
transform.Rotate(-90, 0, 0);
}
}
controller.Move(new Vector3(0, 0, vInput) * mSpeed * Time.deltaTime);
}strong text