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

首先,要为被观测对象设定一个子对象(用于添加组件和放入摄像机),然后再拖出(这样就能保持这个空物体的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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值