Unity学习笔记——利用脚本实现对一个物体的第三人称观察

来源:互联网 发布:久其软件 决算 编辑:程序博客网 时间:2024/05/16 01:45

首先,要为被观测对象设定一个子对象(用于添加组件和放入摄像机),然后再拖出(这样就能保持这个空物体的transform和被观测物体一致。),将摄像机拖入这个空物体之中作为子物体。其中是针对空物体的视角来进行旋转,针对它的子物体摄像机来进行缩放

脚本代码为

using UnityEngine;using System.Collections;public class FYLcamera : MonoBehaviour {    public Transform target;//被观测物体    public Transform childCamera;//摄像机    public float rotateSpeed;//旋转速度    public float scaleSpeed;//缩放速度    public float minDistance;//最近缩放位置    public float maxDistance;//最远缩放位置    private float currentScale;//现有的缩放大小    private Vector3 currentRotation;//现有的旋转角    private Vector3 lastMousePosition;//记录鼠标上次的位置    // Use this for initialization    void Start () {        currentScale = childCamera.position.z;//初始化缩放大小        currentRotation = transform.eulerAngles;//初始化欧拉角        lastMousePosition = Input.mousePosition;    }    // Update is called once per frame    void Update () {        Vector3 mouseDelta = Input.mousePosition - lastMousePosition;//计算鼠标位移        lastMousePosition = Input.mousePosition;        if (Input.GetMouseButton (1)) {//如果使用鼠标右键            currentRotation.x += mouseDelta.y * rotateSpeed * Time.deltaTime;            currentRotation.y += mouseDelta.x * rotateSpeed * Time.deltaTime;        //因为旋转方向和鼠标拖动方向正好相反,所以用以上公式计算旋转量        }        currentScale += -Input.mouseScrollDelta.y * scaleSpeed * Time.deltaTime;//计算缩放值,因为我的摄像机是反的,所以要取负数        currentScale = Mathf.Clamp (currentScale, minDistance, maxDistance);//取闭区间,使得缩放值一直在规定的范围之内        transform.position = target.position;//空物体的坐标跟随被观测物体        transform.eulerAngles = currentRotation;//欧拉角设定为当前的旋转量       childCamera.localPosition = new Vector3 (0, 0, currentScale);//设定摄像机的缩放距离。    }}
0 0