Move an object without rotating it and in the direction the camera is facing

Hello,

I don’t know what to do to fix this crappy code I wrote: I have an object and I want to move it in the direction the camera is facing without rotating the object, I also want to be able to move right, left and back. This code works, but here’s the twist: I want to rotate the object in the direction the camera is facing if I press a button. So far so good, the object rotates.

BUT

If I try to move the references are changed, if I want to go forward the object goes to the left. It is as if by rotating 90 degrees the reference system rotates as well.

I explain better:

  • facing 0 degrees, I go forward;

  • facing 90 degrees, I go right (180 degrees)

  • facing 180 degrees I go back (0 degrees)

  • facing 270 degrees I go left (180 degrees)

HELP PLEASE!

Public Camera propCamera;

float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 moveDir = new Vector3(horizontal, 0f, vertical).normalized;
           
    if(moveDir.magnitude >= 0.1f)
            {
                float targetAngle = Mathf.Atan2(horizontal, vertical) * Mathf.Rad2Deg + propCamera.transform.eulerAngles.y;
                Vector3 moveDirUpdated = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
               
                moveAmount = Vector3.SmoothDamp(moveAmount, moveDirUpdated.normalized * (Input.GetKey(KeyCode.LeftShift) ? sprintSpeed : walkSpeed),
                    ref smoothMoveVelocity, smoothTime);
            }

Problem the first: When you normalize moveDir, its magnitude is always going to be 1. You should do the normalizing after that if statement.

Problem the second: You turn a vector into a rotation only to turn it back into a vector, which is wasteful and overcomplicated (making it harder to track down issues). Also, in the process, you use the Y component of the camera’s Euler angles alone, which is asking for trouble - Euler angles in general are flaky.

What you need is to convert the input vector in camera space to a direction vector in world space, and you don’t need to go through Quaternion for that.

Vector3 worldMovementVector = propCamera.transform.TransformDirection(moveDir);

Thanks! Anyway, I put in the line you wrote but the object moves in the same way as it did before: if I rotate the object, the system rotates too and it doesn’t go forward if I press forward…

Post the part of the code that actually applies this logic to the transform?

 private void FixedUpdate()
    {
            rb.MovePosition(rb.position + transform.TransformDirection(moveAmount) * Time.fixedDeltaTime);
    }

You didn’t use the variable in my code in that, so of course the behavior didn’t change. (When you do, don’t use .TransformDirection; worldMovementVector is already in the correct space for that)

Oh oh, stupid me.
Now it’s working!
Thanks for the help!!!