Unity学习笔记——利用脚本实现对一个物体的第三人称观察
2016-03-01 21:47
573 查看
首先,要为被观测对象设定一个子对象(用于添加组件和放入摄像机),然后再拖出(这样就能保持这个空物体的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);//设定摄像机的缩放距离。 } }
相关文章推荐
- unitywebgl发展计划
- 解决Unity3d 图片黑边问题
- Unity如何在Editor下执行协程(coroutine)
- Angry Birds Clone in Unity 3D (source code included)
- MouseFollowRotation Unity3d鼠标点击旋转相机
- Unity 基础
- Unity3D 优化之路(一):DrawCall
- Unity3d 解析文本执行已注册的自定函数
- unity3d,android平台下,高德地图定位
- Unity3D学习笔记(2)——用GUI制作井字棋游戏
- unity中的几个坑
- unity 切圆角矩形 --shader编程
- unity中的Transform类
- unity实现玻璃效果
- unity实现玻璃效果
- unity中的WWW通讯问题
- [Unity2d系列教程] 005.Unity如何使用外部触控插件FingerGuesture
- unity中事件分发系统 EventDispatcher
- Unity3D教程宝典之Shader篇 基本知识
- Unity3d获得android和ios设备的唯一标识