正交相机变焦,专注于特定点

时间:2013-09-02 11:07:05

标签: unity3d orthographic

我有一个正交相机,并希望在特定点实现缩放功能。即,想象你有一张照片,想要缩放到图片的特定部分。

我知道如何放大,问题是将相机移动到具有所需区域的位置。

我该怎么办?

2 个答案:

答案 0 :(得分:0)

相机的orthographicSize是视口上半部分中的世界空间单位数。如果它是0.5,则1个单位的立方体将完全填充视口(垂直)。

因此,要放大目标区域,请将相机置于其上(通过将(x,y)设置为目标的中心)并将orthographicSize设置为区域高度的一半。

这是一个居中和缩放到对象范围的示例。 (用LMB缩放;'R'重置。)

public class OrthographicZoom : MonoBehaviour
{
    private Vector3 defaultCenter;
    private float defaultHeight; // height of orthographic viewport in world units

    private void Start()
    {
        defaultCenter = camera.transform.position;
        defaultHeight = 2f*camera.orthographicSize;
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Collider target = GetTarget();
            if(target != null)
                OrthoZoom(target.bounds.center, target.bounds.size.y); // Could directly set orthographicSize = bounds.extents.y
        }

        if (Input.GetKeyDown(KeyCode.R))
            OrthoZoom(defaultCenter, defaultHeight);
    }


    private void OrthoZoom(Vector2 center, float regionHeight)
    {
        camera.transform.position = new Vector3(center.x, center.y, defaultCenter.z);
        camera.orthographicSize = regionHeight/2f;
    }


    private Collider GetTarget()
    {
        var hit = new RaycastHit();
        Physics.Raycast(camera.ScreenPointToRay(Input.mousePosition), out hit);
        return hit.collider;
    }
}

答案 1 :(得分:0)

希望您发现此代码示例有用,应该是复制/粘贴。 注意:此脚本假定它附加到相机对象,否则您应该将变换调整为相机对象参考。

private float lastZoomDistance = float.PositiveInfinity; // remember that this should   be reset to infinite on touch end
private float maxZoomOut = 200;
private float maxZoomIn = 50;
private float zoomSpeed = 2;

void Update() {

if (Input.touchCount >= 2) {

    Vector2 touch0, touch1;
    float distance;
    Vector2 pos = new Vector2(transform.position.x, transform.position.y);
    touch0 = Input.GetTouch(0).position - pos;
    touch1 = Input.GetTouch(1).position - pos;

    zoomCenter = (touch0 + touch1) / 2;

    distance = Vector2.Distance(touch0, touch1);
    if(lastZoomDistance == float.PositiveInfinity) {
        lastZoomDistance = distance;
    } else {
        if(distance > lastZoomDistance && camera.orthographicSize + zoomSpeed <= maxZoomOut) {
            this.camera.orthographicSize = this.camera.orthographicSize + zoomSpeed;
            // Assuming script is attached to camera - otherwise, change the transform.position to the camera object
            transform.position = Vector3.Lerp(transform.position, zoomCenter, Time.deltaTime);
        } else if(distance < lastZoomDistance && camera.orthographicSize - zoomSpeed >= maxZoomIn) {
            this.camera.orthographicSize = this.camera.orthographicSize - zoomSpeed;
            transform.position = Vector3.Lerp(transform.position, zoomCenter, Time.deltaTime);
        }
    }
    lastZoomDistance = distance;
}

}