相機視角跟隨 的幾種方式👻
因為平時無論是做游戲,還是寫寫小Demo,讓相機跟隨物體移動進行視角控制還是用的挺多的
下面就來介紹幾種可以控制攝像機視角跟隨角色物體移動的幾種方式, (忽略我隨意搭建的測驗場景,low的很…哈哈)
這是簡單控制物體移動的腳本,掛到物體上移動測驗用的
寫的很簡單,通過按鍵盤上的上下左右就可以進行移動和轉身
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerTest1 : MonoBehaviour
{
[Header("移動速度")]
public float movespeed = 5f;
[Header("轉身速度")]
public float turnspeed = 5f;
private float hor;
private float ver;
void Update()
{
hor = Input.GetAxis("Horizontal");
ver = Input.GetAxis("Vertical");
//前后移動
transform.position += ver * transform.forward * Time.deltaTime * movespeed;
//左右轉身
transform.eulerAngles += hor * Vector3.up * turnspeed;
}
}
第三人稱視角相機跟隨🎃
因為控制視角跟隨的方法有很多種,在這里就只介紹三種方法,功能各有所不同,不過區別不是很大,都是第三人稱視角來的~~
以下都是通過在Unity界面直接將要追蹤的物體拖到攝像機的腳本上的
①普通攝像機視角跟隨🎅
直接將場景中的Camera拖到該物體上

這是最簡便的方法,也不用寫代碼,將攝像機掛上去即可,
優點:操作簡單,都不用寫代碼的
缺點:旋轉的時候效果不好,頭暈目眩~
②普通攝像機視角跟隨🎄
宣告一個方向向量,計算攝像機指向玩家的方向偏移量,從而計算出出攝像機的位置,然后讓攝像機一直隨著這個數值即可,
腳本掛載到攝像機上即可

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cameraTest : MonoBehaviour
{
//跟隨的目標
public Transform target;
//方向向量
private Vector3 dir;
private void Start()
{
//計算攝像機指向玩家的方向偏移量
dir = target.position - transform.position;
}
private void Update()
{
//時時刻刻計算攝像機的跟隨位置
Vector3 bastPos = target.position - dir;
transform.position = bastPos;
}
}
③可以通過滑鼠滑輪控制視角縮放的跟隨🎁
這個的視角跟隨效果與第二個類似,多了一個通過滑鼠滑輪控制視角縮放的效果
代碼

using UnityEngine;
using System.Collections;
public class camera : MonoBehaviour
{
public Transform target;
Vector3 offset;
// Use this for initialization
void Start()
{
offset = transform.position - target.position;
}
// Update is called once per frame
void Update()
{
transform.position = target.position + offset;
Rotate();
Scale();
}
//縮放
private void Scale()
{
float dis = offset.magnitude;
dis -= Input.GetAxis("Mouse ScrollWheel") * 5;
Debug.Log("dis=" + dis);
if (dis < 10 || dis > 40)
{
return;
}
offset = offset.normalized * dis;
}
//左右上下移動
private void Rotate()
{
if (Input.GetMouseButton(1))
{
Vector3 pos = transform.position;
Vector3 rot = transform.eulerAngles;
//圍繞原點旋轉,也可以將Vector3.zero改為 target.position,就是圍繞觀察物件旋轉
transform.RotateAround(Vector3.zero, Vector3.up, Input.GetAxis("Mouse X") * 10);
transform.RotateAround(Vector3.zero, Vector3.left, Input.GetAxis("Mouse Y") * 10);
float x = transform.eulerAngles.x;
float y = transform.eulerAngles.y;
Debug.Log("x=" + x);
Debug.Log("y=" + y);
//控制移動范圍
if (x < 20 || x > 45 || y < 0 || y > 40)
{
transform.position = pos;
transform.eulerAngles = rot;
}
// 更新相對差值
offset = transform.position - target.position;
}
}
}
④相機一直拍攝角色的后背的視角🔔
這個相機跟隨是一直拍角色后背的視角,會自動調整

using UnityEngine;
using System.Collections;
//相機一直拍攝主角的后背
public class cameraT4 : MonoBehaviour
{
public Transform target;
public float distanceUp = 15f;
public float distanceAway = 10f;
public float smooth = 2f;//位置平滑移動值
public float camDepthSmooth = 5f;
void Update()
{
// 滑鼠軸控制相機的遠近
if ((Input.mouseScrollDelta.y < 0 && Camera.main.fieldOfView >= 3) || Input.mouseScrollDelta.y > 0 && Camera.main.fieldOfView <= 80)
{
Camera.main.fieldOfView += Input.mouseScrollDelta.y * camDepthSmooth * Time.deltaTime;
}
}
void LateUpdate()
{
//相機的位置
Vector3 disPos = target.position + Vector3.up * distanceUp - target.forward * distanceAway;
transform.position = Vector3.Lerp(transform.position, disPos, Time.deltaTime * smooth);
//相機的角度
transform.LookAt(target.position);
}
}
⑤ 有檔位的攝像機視角跟隨(較復雜) 🎉
原理是通過射線檢測當前攝像機與物體的角度來改變攝像機的位置,因為在一般游戲場景中有時候會有其他物體,比如墻體之類的會擋住玩家,所以通過這種方法可以有效的控制視角
代碼
using System;
using UnityEngine;
public class camera : MonoBehaviour
{
//跟隨的目標
public Transform followTarget;
//方向向量
private Vector3 dir;
//射線碰撞檢測器
private RaycastHit hit;
//攝像機移動速度
public float moveSpeed;
//攝像機旋轉速度
public float turnSpeed;
//攝像機觀察的檔位【可選的視角位置的個數】
public const int camera_watch_gear = 5;
//觀察玩家身體偏移量
public const float PLAYER_WATCHBODY_OFFSET = 1f;
private void Start()
{
//計算方向向量【攝像機指向玩家】
dir = followTarget.position - transform.position;
}
private void Update()
{
FollowMethod();
}
/// <summary>
/// 跟隨演算法
/// </summary>
private void FollowMethod()
{
//時時刻刻計算攝像機的跟隨的最佳位置
Vector3 bestWatchPos = followTarget.position - dir;
//計算跟隨目標頭頂的俯視位置【不好、但可以保證看到玩家】
Vector3 badWatchPos = followTarget.position + Vector3.up *
(dir.magnitude);
//定義所有觀察點的陣列【陣列長度就為檔位個數】
Vector3[] watchPoints = new Vector3[camera_watch_gear];
//設定陣列的起始點
watchPoints[0] = bestWatchPos;
watchPoints[watchPoints.Length - 1] = badWatchPos;
for (int i = 1; i <= watchPoints.Length - 2; i++)
{
//計算中間觀察點的坐標
watchPoints[i] = Vector3.Lerp(bestWatchPos, badWatchPos,
(float)i / (camera_watch_gear - 1));
}
//宣告最合適的觀察點【初值是最初的觀察點】
Vector3 suitablePos = bestWatchPos;
//遍歷所有的觀察點
for (int i = 0; i < watchPoints.Length; i++)
{
//檢測該點是否可以看到玩家
if (CanSeeTarget(watchPoints[i]))
{
//選出最合適的點
suitablePos = watchPoints[i];
//跳出回圈
break;
}
}
//插值移動到合適的位置
transform.position = Vector3.Lerp(transform.position,
suitablePos, Time.deltaTime * moveSpeed);
//計算該點指向玩家的方向向量
Vector3 crtDir = followTarget.position +
Vector3.up * PLAYER_WATCHBODY_OFFSET
- suitablePos;
//將方向向量轉成四元數
Quaternion targetQua = Quaternion.LookRotation(crtDir);
//Lerp過去
transform.rotation = Quaternion.Lerp(transform.rotation,
targetQua, Time.deltaTime * turnSpeed);
//歐拉角修正
transform.eulerAngles = new Vector3(transform.eulerAngles.x, 0, 0);
}
/// <summary>
/// 檢測該點可以看到玩家
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
private bool CanSeeTarget(Vector3 pos)
{
//計算此時的方向向量
Vector3 crtDir = followTarget.position +
Vector3.up * PLAYER_WATCHBODY_OFFSET - pos;
//發射物理射線
if (Physics.Raycast(pos, crtDir, out hit))
{
//射線打到的物件是玩家,說明該點可以看到玩家
if (hit.collider.CompareTag("Player"))
{
return true;
}
}
return false;
}
}
第一人稱視角相機跟隨🎈
①簡單相機跟隨滑鼠移動來形成視角跟隨的效果🌟
將腳本掛到相機上,然后相機設為移動物體的子物體
代碼
using UnityEngine;
using System.Collections;
/// <summary>
/// 滑鼠控制相機旋轉
/// </summary>
public class cameraT5 : MonoBehaviour
{
private void Update()
{
float x = Input.GetAxis("Mouse X");
float y = Input.GetAxis("Mouse Y");
if (x != 0 || y != 0)
RotateView(x, y);
}
public float speed = 10;
private void RotateView(float x, float y)
{
x *= speed * Time.deltaTime;
y *= speed * Time.deltaTime;
//沿Y軸旋轉
transform.Rotate(-y, 0, 0);
//左右旋轉,需沿直接坐標系y軸,不然會像坐飛機倒轉一樣暈視角
transform.Rotate(0, x, 0, Space.World);
}
}
②通過移動滑鼠玩家方向改變的同時,調整相機視角的變化💫
將腳本掛到移動的物體上,然后相機設為移動物體的子物體,這個是滑鼠來控制方向的,可能效果不是很好
代碼
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cameraT2 : MonoBehaviour
{
//注意列舉的使用,可以用名稱設定值,而不是用魔術數字,這樣有利于代碼的理解和閱讀,是良好的習慣
public enum RotationAxes
{
MouseXAndY = 0,
MouseX = 1,
MouseY = 2
}
public float sensitivityHor = 9.0f;//水平旋轉速度
public float sensitivityVert = 9.0f; //垂直旋轉速度,靈敏度
public float minimumVert = -90.0f;
public float maximumVert = 90.0f;
private float _rotationX = 0;//為垂直角度宣告一個變數
public RotationAxes axes = RotationAxes.MouseXAndY; //使得變數暴露在組件里,可以在Unity里可視化更改
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (axes == RotationAxes.MouseX)
{
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityHor, 0);
//水平旋轉,所以固定了z軸,繞著z軸在四周旋轉,
}
else if (axes == RotationAxes.MouseY)
{ //垂直方向旋轉的代碼
_rotationX -= Input.GetAxis("Mouse Y") * sensitivityVert; //基于滑鼠增加垂直角度
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert); //限制上下看的范圍
float rotationY = transform.localEulerAngles.y;//保持y的角度
transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0); //使用新的值存盤固定了的旋轉前的水平旋轉資訊并增加上下方向旋轉的移動
}
else
{
// 同時可以水平和垂直方向的旋轉
_rotationX -= Input.GetAxis("Mouse Y") * sensitivityVert;
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);
float delta = Input.GetAxis("Mouse X") * sensitivityHor; //delta是旋轉的變化量,一般數學上也會把變化量協作delta
float rotationY = transform.localEulerAngles.y + delta;
transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);
}
}
}
總結💬
以上就是分別介紹了第三人稱和第一人稱視角控制的幾種方法,當然還有更多的辦法,這里只是介紹了幾種,有需求可以再去深入研究一個符合自己的視角控制哦

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/282389.html
標籤:其他
上一篇:C語言專案2------------------掃雷(帶for回圈遞回展開和標記功能)
下一篇:18.走方格的方案數
