Unity3d 旋轉相機檢視物體(指令碼掛在相機上,要檢視的物體作為中心點)
阿新 • • 發佈:2018-12-14
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; } } }