unity3d 平移摄像机仅在一个方向移动,而不是在所有4个方向移动

iszxjhcz  于 2022-12-27  发布在  其他
关注(0)|答案(1)|浏览(149)

为什么在以下代码中vector 3移动的X坐标始终为0?Camera.main.ScreenToWorldPoint方法返回的X分量始终为0,即使Input.mounsPosition提供X!=0。

private void Pan()
    {

        // save initial position of mouse whenn RMB pressed for first time
        if(Input.GetMouseButtonDown(1))
        {
            mouseWorldPosStart = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        }

        // calculate distance between initial mouse position and current mouse position
        if (Input.GetMouseButton(1))
        {
            var newMousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

            Vector3 mouseWorldPosDiff = mouseWorldPosStart - newMousePosition;
            Debug.Log( "Initial position: " + mouseWorldPosStart + " Delta = " + mouseWorldPosDiff + " New Position: " + newMousePosition );
            //move the camere by the distance
            transform.position += mouseWorldPosDiff;
        }
    }

目标是编写摄像机平移功能的代码。

1bqhqjot

1bqhqjot1#

我认为主要的问题将是,当你移动相机时,即使没有进一步移动光标,ScreenToWorldPoint也已经返回了一个新值。
你更需要保存原点,然后用一个delta来移动相机。我想可能是像eidogg这样的东西。

// in general cache the reference
[SerializeField] private Camera camera;

// world space point where we started to pan 
private Vector3 panStart;
private Vector3 initialPosition;

private void Awake()
{
    if(!camera) camera = Camera.main;
}

void Update ()
{
    // only true the first frame of the panning 
    if (Input.GetMouseButtonDown(1))
    {
        initialPosition = camera.transform.position;
        panStart = camera.transform.InverseTransformPoint(camera.ScreenToWorldPoint(Input.mousePosition));
    }

    if (Input.GetMouseButton(1))
    {
        var pan = panStart - camera.transform.InverseTransformPoint(camera.ScreenToWorldPoint(Input.mousePosition));
        camera.transform.position = initialPosition + camera.transform.TransformVector(pan);
    }
}

这里的技巧是,我们使用局部空间来计算摇摄,然后将其转换回全局空间,以便将此增量添加到初始世界空间位置。这样,相机本身的移动不会直接影响ScreenToWorldPoint增量

相关问题