Unity3d 旋转相机查看物体(脚本挂在相机上,要查看的物体作为中心点)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CamRotate : MonoBehaviour
{
    private float ClampYMin=15;
    private float ClampYMax = 89;

    float x = 0f;
    float y = 0f;
    float speed = 100f;
    float distance = 10f;

    [SerializeField]
    private GameObject center;


    // Use this for initialization
    void Start()
    {
        distance = Vector3.Distance(this.transform.position, center.transform.position);

    }
 
    private void OnGUI()
    {
        if (Event.current.type == EventType.MouseDrag)
        {
            CameraRotate();
        }
    }
    void CameraRotate()
    {
       
        if (Input.GetMouseButton(0) )
        {
            x = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * speed * Time.deltaTime;
            y = transform.localEulerAngles.x + Input.GetAxis("Mouse Y") * speed * Time.deltaTime;
            // y = Mathf.Clamp(y, 0, 100);
            y = ClampAngle(y, ClampYMin, ClampYMax);
            Quaternion q = Quaternion.Euler(y, x, 0);//摄像机偏转角度  
            Vector3 direction = new Vector3(0, 0, -distance);//摄像机距离物品的距离 
            transform.localRotation = q;//让摄像机始终转向物品  
            transform.localPosition = center.transform.localPosition + q * direction;

        }

    }



}

猜你喜欢

转载自blog.csdn.net/m0_37981386/article/details/84790619
今日推荐