unity摄像机脚本
Posted 三页菌
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了unity摄像机脚本相关的知识,希望对你有一定的参考价值。
直接挂载在摄像机上面即可
1.摄像机自由平移
using UnityEngine; using System.Collections; /// <summary> /// 摄像机视角自由移动 /// </summary> public class CameraFreeMove : MonoBehaviour { public float moveSpeed = 10; // 设置相机移动速度 void Update() { // 当按住鼠标右键的时候 if (Input.GetMouseButton(0)) { // 获取鼠标的x和y的值,乘以速度和Time.deltaTime是因为这个可以是运动起来更平滑 float h = Input.GetAxis("Mouse X") * moveSpeed * Time.deltaTime; float v = Input.GetAxis("Mouse Y") * moveSpeed * Time.deltaTime; // 设置当前摄像机移动,y轴并不改变 // 需要摄像机按照世界坐标移动,而不是按照它自身的坐标移动,所以加上Spance.World this.transform.Translate(v, 0, -h, Space.World); } } }
2.使用鼠标滚轮和双指触摸进行缩放
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraZoom : MonoBehaviour { public float maxDistance;//最大距离 public float minDistance;//最小距离 public float scaleSpeed;//缩放速度 public float mouseSpeed;//缩放速度 private Touch oldTouch1; //上次触摸点1(手指1) private Touch oldTouch2; //上次触摸点2(手指2) // Use this for initialization void Start () { //FairyGUI.GObject a; //a.visible = false; } // Update is called once per frame void Update () { ZoomCamera(); MouseZoomCamera(); } /// <summary> /// 手势屏幕缩放 /// </summary> private void ZoomCamera() { //至少得要2个触摸点 if (Input.touchCount < 2) { return; } //多点触摸, 放大缩小 Touch newTouch1 = Input.GetTouch(0); Touch newTouch2 = Input.GetTouch(1); //第2点刚开始接触屏幕, 只记录,不做处理 if (newTouch2.phase == TouchPhase.Began) { oldTouch2 = newTouch2; oldTouch1 = newTouch1; return; } //计算老的两点距离和新的两点间距离,变大要放大模型,变小要缩放模型 float oldDistance = Vector2.Distance(oldTouch1.position, oldTouch2.position); float newDistance = Vector2.Distance(newTouch1.position, newTouch2.position); //两个距离之差,为正表示放大手势, 为负表示缩小手势 float offset = newDistance - oldDistance; Vector3 originalPos = transform.position; Quaternion originalRotation = transform.rotation; transform.position += offset * transform.forward * scaleSpeed * Time.deltaTime; //临时判断值 float cameraY = transform.position.y; if (cameraY < minDistance || cameraY > maxDistance) { transform.position = originalPos; transform.rotation = originalRotation; } //重新计算 cameraY = transform.position.y; //记住最新的触摸点,下次使用 oldTouch1 = newTouch1; oldTouch2 = newTouch2; } /// <summary> /// 鼠标滚轮缩放 /// </summary> private void MouseZoomCamera() { //获取滚轮的值 float mouseScroll = Input.GetAxis("Mouse ScrollWheel"); if (Mathf.Abs(mouseScroll) > 0) { //print("hua"); Vector3 originalPos = transform.position; Quaternion originalRotation = transform.rotation; transform.position += mouseScroll * transform.forward * mouseSpeed * Time.deltaTime; //临时判断值 float cameraY = transform.position.y; if (cameraY < minDistance || cameraY > maxDistance) { transform.position = originalPos; transform.rotation = originalRotation; } //cameraY = transform.position.y; //print(distance.magnitude); } } }
以上是关于unity摄像机脚本的主要内容,如果未能解决你的问题,请参考以下文章
unity 怎么设置分辨率?unity摄像头怎么设置分辨率?
Unity3D鼠标控制摄像机“左右移动控制视角+WASD键盘控制前后左右+空格键抬升高度”脚本
Unity3D鼠标控制摄像机“左右移动控制视角+WASD键盘控制前后左右+空格键抬升高度”脚本