Moving an object in its local X/Z relative to the camera orientation

I have an object that is aligned correctly with the ground plane and I want to move it along its local x/z axis but in a direction that is relative to the cameras orientation. Needs to be camera relative forward and left and right.

I’m having a hard time figuring out where to start. Any suggestions?

That almost worked. Had to set dir.y=0; then it worked like a charm.

–

If it answered your question, please click the checkmark next to the answer to close it out.

–

2 Answers

2

There are a couple of different ways to approach this problem. Below is one approach that I think is a bit easier to understand:

 var dir : Vector3;
 dir = Camera.main.transform.forward;  // forward
// dir = -Camera.main.transform.forward;  // back
// dir = Camera.main.transform.right;  // right;
// dir = -Camera.main.transsform.left;  // left;

 dir.y = transform.position.y
 dir.Normalize();
 transform.Translate(dir * speed * Time.deltaTime);

The commented out lines are for the other three directions.

Question, while it is true that this does work for forward, back, left, and right. What about diagonals? Since the camera is facing slightly down that means the the normalized direction will not be equally forward/back and left/right. The left/right will have a greater value than the forward/back

–

While the accepted answer works, I also wanted to rotate the object to face the direction it’s moving in. I ended up coming up with this, figured I’d post it for others who stumble across this answer:

private void RotateRelativeToCamera(Vector3 direction, Camera cam) {
	// rotate given direction by the camera's rotation
	Vector3 camDir = cam.transform.rotation * direction;
	
	// add result to object's location to get relative direction
	Vector3 objectDir = transform.position + camDir;
	
	// create quaternion facing direction
	Quaternion targetRotation = Quaternion.LookRotation(objectDir - transform.position);
	
	// constrain rotation to the Y axis
	Quaternion constrained = Quaternion.Euler(0.0f, targetRotation.eulerAngles.y, 0.0f);
	
	// slerp rotation
	transform.rotation = Quaternion.Slerp(transform.rotation, constrained, Time.deltaTime * this.RotationDamping);
}

Then, in update() I have something like

if(movingLeft)
    this.RotateRelativeToCamera(Vector3.left, Camera.main);

if(movingForward)
   this.RotateRelativeToCamera(Vector3.forward, Camera.main);

// etc...

And to make the object move forward,

rigidbody.velocity = rigidbody.rotation * new Vector3(0.0f, 0.0f, this.MovementSpeed);