简体   繁体   English

相对于相机移动对象 旋转时移动到错误的方向

[英]Move object relative to camera move to wrong direction when rotate it

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使用transform.Translate参数的最后一个 relativeTo => 我只需要在 x 和 z 轴上是相对的,这也适用于 y 轴
  • 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多余的东西我想: 东西更多的东西

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 Translate有一个可选参数Space relativeTo ,默认情况下(如果未提供)是Space.Self

Applies transformation relative to the local coordinate system.应用相对于局部坐标系的变换。

eg例如

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 globalSpace.World instead因此,如果您想忽略任何旋转和缩放,请改用全局Space.World

Applies transformation relative to the world coordinate system.应用相对于世界坐标系的变换。

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

or also或者也

transform.position += panSpeed * Time.deltaTime * movement;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM