unity的摄像机脚本
Posted allyh
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了unity的摄像机脚本相关的知识,希望对你有一定的参考价值。
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; public class MainCamera : MonoBehaviour public Transform target; public float targetHeight = 1.2f; public float distance = 8.0f; public float offsetFromWall = 0.1f; public float maxDistance = 15; public float minDistance = 3f; public float xSpeed = 200.0f; public float ySpeed = 200.0f; public int yMinLimit = 0; public int yMaxLimit = 80; public int zoomRate = 40; public float rotationDampening = 3.0f; public float zoomDampening = 5.0f; public LayerMask collisionLayers = -1; private float xDeg = -53.2f; private float yDeg = 22.4f; private float currentDistance; private float desiredDistance; private float correctedDistance; void Start() currentDistance = distance; //当前距离 desiredDistance = distance; //默认距离 correctedDistance = distance; //需要修正的距离 void LateUpdate() target = GameObject.FindGameObjectWithTag("Player").transform; Vector3 vTargetOffset; if (!target) return; if (Input.GetMouseButton(1)) xDeg += Input.GetAxis("Mouse X") * xSpeed * 0.02f; yDeg -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f; yDeg = ClampAngle(yDeg, yMinLimit, yMaxLimit); xDeg = ClampAngle(xDeg, -360, 360); Quaternion rotation = Quaternion.Euler(yDeg, xDeg, 0); desiredDistance -= Input.GetAxis("Mouse ScrollWheel") * Time.deltaTime * zoomRate * Mathf.Abs(desiredDistance); //滚珠移动摄像头与人的距离 correctedDistance = desiredDistance; vTargetOffset = new Vector3(0, -targetHeight, 0); Vector3 position = target.position - (rotation * Vector3.forward * desiredDistance + vTargetOffset); //摄像机与人之间的向量 RaycastHit collisionHit; Vector3 trueTargetPosition = new Vector3(target.position.x, target.position.y + targetHeight, target.position.z); //修改人身上的射线发出点坐标 bool isCorrected = false; if (Physics.Linecast(trueTargetPosition, position, out collisionHit, collisionLayers.value)) correctedDistance = Vector3.Distance(trueTargetPosition, collisionHit.point) - offsetFromWall; isCorrected = true; currentDistance = !isCorrected || correctedDistance > currentDistance ? Mathf.Lerp(currentDistance, correctedDistance, Time.deltaTime * zoomDampening) : correctedDistance; currentDistance = Mathf.Clamp(currentDistance, minDistance, maxDistance); position = target.position - (rotation * Vector3.forward * currentDistance + vTargetOffset); transform.rotation = rotation; transform.position = position; private static float ClampAngle(float angle, float min, float max) if (angle < -360) angle += 360; if (angle > 360) angle -= 360; return Mathf.Clamp(angle, min, max);
以上是关于unity的摄像机脚本的主要内容,如果未能解决你的问题,请参考以下文章