Unity 相機平移、縮放、旋轉


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Move : MonoBehaviour
{

float speed = 20;
public float distance_v;
public float distance_h;
public float rotation_H_speed = 1;
public float rotation_V_speed = 1;
public float max_up_angle = 80;              //越大,頭抬得越高
    public float max_down_angle = -60;            //越小,頭抬得越低


    private float current_rotation_H;      //水平旋轉結果
    private float current_rotation_V;  //垂直旋轉結果
    void LateUpdate()
{
// 旋轉
if (Input.GetMouseButton(1))
{
//控制旋轉
current_rotation_H += Input.GetAxis("Mouse X") * rotation_H_speed;
current_rotation_V += Input.GetAxis("Mouse Y") * rotation_V_speed;
//current_rotation_V = Mathf.Clamp(current_rotation_V, max_down_angle, max_up_angle); //限制垂直旋轉角度
transform.localEulerAngles = new Vector3(-current_rotation_V, current_rotation_H, 0f);

//改變位置,以跟蹤的目標為視野中心,且視野中心總是面向follow_obj
//transform.position = follow_obj.position;
transform.Translate(Vector3.back * distance_h, Space.Self);
transform.Translate(Vector3.up * distance_v, Space.World);          //相對於世界坐標y軸向上
}

// 平移
if (Input.GetMouseButton(2))
{

this.transform.localPosition -= new Vector3(Input.GetAxis("Mouse X") * rotation_H_speed, Input.GetAxis("Mouse Y") * rotation_V_speed, 0f);

}
}
// Use this for initialization
void Start()
{

}

// Update is called once per frame
void Update()
{
// 移動
if (Input.GetKey(KeyCode.A)) //左移
{
transform.Translate(Vector3.left * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D)) //右移
{
transform.Translate(Vector3.right * speed * Time.deltaTime);

}
if (Input.GetKey(KeyCode.W)) //前移
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);

}
if (Input.GetKey(KeyCode.S)) //后移
{
transform.Translate(Vector3.back * speed * Time.deltaTime);

}

// 縮放
if (Input.GetAxis("Mouse ScrollWheel") != 0)
{
//獲取鼠標滾輪的滑動量
float wheel = Input.GetAxis("Mouse ScrollWheel") * Time.deltaTime * 5000;

//改變相機的位置
this.transform.Translate(Vector3.forward * wheel);
//float distance = this.transform.position.y + wheel;
//this.transform.SetPositionAndRotation(new Vector3(this.transform.position.x, distance, this.transform.position.z),this.transform.rotation);
}
}
}

直接將代碼放到相機上即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM