您的位置:首页 > 移动开发 > Unity3D

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);//设定摄像机的缩放距离。
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: