简体   繁体   English

无论局部角度如何,在全局 XZ 平面上移动相机(Unity)

[英]Move camera on global XZ plane regardless of local angle (Unity)

I am scripting the movement of the main camera on the XZ axis.我正在编写主摄像机在 XZ 轴上的移动脚本。 The camera should move horizontally (forward, back, right, left) when the cursor approaches one of the corresponding screen edges.当 cursor 接近相应的屏幕边缘之一时,相机应水平移动(向前、向后、向右、向左)。 The right-left movement works perfectecly;左右运动完美无缺;

To the left向左转

To the right在右边

on the other hand, moving the camera back-forward on its z axis does not work since the camera is slightly rotated.另一方面,在其 z 轴上向后移动相机不起作用,因为相机略微旋转。

Camera tilt相机倾斜

Therefore, when you try to move it forward horizontally, it instead gets closer to the objects.因此,当您尝试将其水平向前移动时,它反而会更靠近对象。

Closer when it should move forward当它应该向前移动时更接近

Away when it should move back当它应该向后移动时离开

      if (Input.mousePosition.y >= Screen.height - brdThcknss)
            { //this line is to be replaced
                //transform.Translate(Vector3.forward * Time.deltaTime * panSpeed);
            }
            if (Input.mousePosition.y <= brdThcknss)
            {//this line is to be replaced
                //transform.Translate(Vector3.back * Time.deltaTime * panSpeed);
            }
            if (Input.mousePosition.x >= Screen.width - brdThcknss)
            {
                transform.Translate(Vector3.right * Time.deltaTime * panSpeed);
            }
            if (Input.mousePosition.x <= brdThcknss)
            {
                transform.Translate(Vector3.left * Time.deltaTime * panSpeed);
            }

It is also necessary to mention that the camera should move througout the XZ plane of the world regardless of the angle of the camera (the camera orbits).还需要提到的是,无论相机的角度如何(相机轨道),相机都应该在世界的 XZ 平面上移动。 What could I replace the commented lines for so that the camera performs the desired movement?我可以用什么替换注释行,以便相机执行所需的运动?

AresCaelum's comment is likely correct, but if you'd like to avoid the Translate function altogether, you could simply assign a new Vector3 to the object's position. AresCaelum 的评论可能是正确的,但如果您想完全避免 Translate function,您可以简单地将新 Vector3 分配给对象的 position。

Something like:就像是:

transform.position = new Vector3(newX, transform.position.y, newZ);

it could also be done on the localPosition like它也可以在 localPosition 上完成,例如

transform.localposition = new Vector3(x,y,z);

If you want to avoid creating a new Vector3 every time you're running this code, you could simply have a Vector3 variable (let's call it 'pos') and do如果您想避免每次运行此代码时都创建一个新的 Vector3,您可以简单地拥有一个 Vector3 变量(我们称之为“pos”)并执行

Vector3 pos = Vector3.zero;

void Start()
{
   pos.y = whateverYValueYouWant;
}

void Update()
{
    pos.x = newX;
    pos.z = newZ;
    transform.position = pos;
}

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

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