- Home /
How to relative movement system based on camera direction
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.
Answer by squidgemelent · Dec 02, 2017 at 12:22 PM
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);
This...kind of works? It's not really what I asked though. The idea is that it moves forward one position based on which direction the camera is looking, regardless of height or angle. With this script, if the camera is angled up, it applies moves the object less, which is exactly what I don't want. Also, it needs to only be in four directions. It can't be diagonally.