化石原创文章,转载请注明来源并保留原文链接


Orbit Camera在观察物体,比如模型观察器中使用,这种camera总是以一个模型为目标,观察点围绕该目标,实现:

1、相机远近操控

2、相机水平旋转操控

3、相机垂直方向抬高、压低

总之,这种相机模型还是非常常用的。下面是代码:

using UnityEngine;
using System.Collections;

public class OrbitCamera : MonoBehaviour
{

    public Transform target;
    public float distance = 5.0f;
    public float xSpeed = 120.0f;
    public float ySpeed = 120.0f;

    public float yMinLimit = -20f;
    public float yMaxLimit = 80f;

    public float distanceMin = .5f;
    public float distanceMax = 15f;

    public float mouseTranslateSpeed = 20;

    float x = 0.0f;
    float y = 0.0f;

    void Start()
    {
        Vector3 angles = transform.eulerAngles;
        x = angles.y;
        y = angles.x;

        Quaternion rotation = Quaternion.Euler(y, x, 0);

        RaycastHit hit;
        if (Physics.Linecast(target.position, transform.position, out hit))
        {
            distance -= hit.distance;
        }
        Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
        Vector3 position = rotation * negDistance + target.position;

        transform.position = position;
    }

    void LateUpdate()
    {
        distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel") * mouseTranslateSpeed, distanceMin, distanceMax);

        if (Input.GetMouseButton(0) && target)
        {
            x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
            y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

            y = ClampAngle(y, yMinLimit, yMaxLimit);
        }

        Quaternion rotation = Quaternion.Euler(y, x, 0);
        transform.rotation = rotation;

        RaycastHit hit;
        if (Physics.Linecast(target.position, transform.position, out hit))
        {
            distance -= hit.distance;
        }
        Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
        Vector3 position = rotation * negDistance + target.position;

        transform.position = position;
    }

    public static float ClampAngle(float angle, float min, float max)
    {
        while(angle < -360f)
            angle += 360F;

        while(angle > 360f)

            angle -= 360f;
        return Mathf.Clamp(angle, min, max);
    }
}

在Unity面板上出现的参数说明:

1、Target:相机观察目标

2、X Speed:鼠标水平移动控制相机旋转的速度,一般不用太大,个位数即可。

3、Y Speed:鼠标上下控制相机仰角的速度,100左右

4、Y Min (Max)Limit:鼠标仰角的最小最大值,-90到90

5、Distance Min:相机离开目标中心的最小距离

6、Distance Max: 相机离开目标中心的最大距离

7、Mouse Translate Speed:鼠标拉近拉远时的速度


化石原创文章,转载请注明来源并保留原文链接