1. 程式人生 > >unity攝像機腳本

unity攝像機腳本

需要 || 進行 縮放 觸摸 設置 cto 世界 nsf

直接掛載在攝像機上面即可

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攝像機腳本