MoveCameraAlignMouse.cs
using UnityEngine;
/// <summary>
/// 通过移动相机位置使观察对象与鼠标对齐
/// </summary>
public class MoveCameraAlignMouse:MonoBehaviour{
//观察对象的Transform
public Transform objTransform;
//主相机
private Camera cam;
//观察对象与相机的z轴距离
private float dz;
private void Start(){
cam=Camera.main;
//计算观察对象与相机的z轴距离
Vector3 objWorldPos=objTransform.position;
dz=objWorldPos.z-cam.transform.position.z;
}
private void Update(){
if(Input.GetMouseButton(0)){
//相机绕观察对象旋转任意角度
cam.transform.RotateAround(objTransform.position,new Vector3(Random.value,Random.value,Random.value),10);
//观察对象的位置
Vector3 objWorldPos=objTransform.position;
//计算鼠标位置的世界坐标(将通过移动相机位置使观察对象与鼠标对齐)
Vector2 targetScreenPos=Input.mousePosition;
Vector3 targetWorldPos=cam.ScreenToWorldPoint(new Vector3(targetScreenPos.x,targetScreenPos.y,dz));
//相机需要偏移的向量
Vector3 offsetWorld=objWorldPos-targetWorldPos;
cam.transform.Translate(offsetWorld,Space.World);
}
}
}