Home > other >  Move object relative to camera move to wrong direction when rotate it
Move object relative to camera move to wrong direction when rotate it

Time:11-12

What I'm trying to do is to move an object relative to where the camera is facing.

I wrote this ugly code so far

private bool ApplyPan_XZ(Vector2 old0, Vector2 new0)
{
    Vector2 panDirection = old0 - new0;

    Vector3 newDirection = new Vector3(panDirection.x, 0f, panDirection.y);

    if (newDirection.magnitude < PanMagnitudeThreshold)
        return false;

    Vector3 movementX = myCamera.right * panDirection.x;
    Vector3 movementZ = myCamera.forward * panDirection.y;
    Vector3 movement = movementX   movementZ;
    movement.y = 0f;

    transform.Translate(panSpeed * Time.deltaTime * movement);

    return true;
}

Basically, I get one old position and a new one, I compare the two positions to get the direction, and then multiply the resulting axis to the camera right and camera forward to get the relative position.

Everything works so far, except when I rotate the transform. In this case, the movement is applied to the forward object for some reason and not anymore to the camera.

What I tried:

  • Used the last relativeTo of transform.Translate parameter => I need to be relative only on the x and z-axis, and this is applied also to the y axis
  • Changed/converted word/local position and vice-versa

What I want to accomplish:

  • Move the transform always relative to the camera, even if I rotate it.

Extra stuff I tried: Stuff More stuff

CodePudding user response:

If you say in general it behaves as expected unless you rotate this object:

Translate has an optional parameter Space relativeTo which by default (if not provided) is Space.Self

Applies transformation relative to the local coordinate system.

e.g.

transform.Translate(Vector3.forward);

would equal using

transform.localPosition  = Vecto3.forward;

or also

transform.position  = transform.forward;

while

transform.Translate(Vector3.forward, Space.World);

equals doing

transform.position  = Vector3.forward;

So if you want to ignore any rotations and scales just use the global Space.World instead

Applies transformation relative to the world coordinate system.

transform.Translate(panSpeed * Time.deltaTime * movement, Space.World);

or also

transform.position  = panSpeed * Time.deltaTime * movement;
  • Related