6

我有一个正交相机,想实现一个特定点的缩放功能。即,假设您有一张图片并且想要缩放到图片的特定部分。

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

我该怎么做?

4

2 回答 2

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;
    }
}
于 2013-09-02T20:40:21.040 回答
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;
}

}
于 2014-06-17T08:11:58.433 回答