I’m coding a game where the player can move a selector throughout the battlefield that is made of several nodes in a 3D grid. The problem is that, when move through the grid it moves perfectly, but as soon as I rotate the camera and change the rotation of the object in increments of 90f, things get really fcked up for no apparent reason and I start getting these weird amounts (the original code is a bit more complex but I simplyfied it):
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
transform.position += Getnextpos(transform.forward * 2);
}
else if (Input.GetKeyDown(KeyCode.S))
{
transform.position += Getnextpos(transform.forward * -2);
}
else if (Input.GetKeyDown(KeyCode.A))
{
transform.position += Getnextpos(transform.right * -2);
}
else if (Input.GetKeyDown(KeyCode.D))
{
transform.position += Getnextpos(transform.right * 2);
}
}
Vector3 Getnextpos(Vector3 moveDirection)
{
Debug.Log("recieving: " + moveDirection);
Debug.Log("move x: " + moveDirection.x + ", y : " + moveDirection.y + ", z: " + moveDirection.z);
return moveDirection;
}
With the code above let’s say I press W and I get this from the Debug.log
recieving: (2.00, 0.00, 0.00)
move x: 2, y : 0, z: 0
Or if I press A:
recieving: (0.00, 0.00, -2.00)
move x: 0, y : 0, z: -2
But when I rotate the camera 90 degrees (and properly changing the object’s rotation) so that the movement is the same relative to the camera, and press W I get this:
recieving: (-2.00, 0.00, 0.00)
move x: -2, y : 0, z: -2.384186E-07
Or this when pressing A:
recieving: (0.00, 0.00, 2.00)
move x: -2.384186E-07, y : 0, z: 2
How can I fix this? This has really sucked up all my patience. TIA!