Simply put, I want my object to move forward (only on the x or z axis, not up and down) based on where the camera is looking. Example: If I press W and I’m looking straight, it will move forward 1 position on the z axis, but if I rotate 90 degrees to the left, when I press W I want it to move forward 1 position on the x axis (or right from the previous position) based on the fact my camera is now looking in a different direction.
Get the camera’s forward vector, which should be a normalized vector (i.e. magnitude of 1). This should essentially tell you what direction the camera is looking. You can then multiply forward vector by your desired speed which should tell you how far you want to move and in what direction. Add this to your current position.
// The camera is assigned public Camera camera; // The calculation var forward = camera.transform.forward; var deltaPosition = forward * objectSpeed * Time.deltaTime; // Modify your object's position gameObject.transform.position += deltaPosition;
In order to not affect your character’s y position, simply don’t apply the calculation to the y property of the vector, so replace the last line with:
// Modify your object's position gameObject.transform.position += new Vector3(deltaPosition.x, 0, deltaPosition.z);