目標
在RTS游戲和一些需要顯示地圖的RPG游戲中,常常出現用鼠標和鍵盤的方向鍵操作 玩家鏡頭的移動,從而達到自由觀看游戲場景的效果
本篇的目標就是實現這一效果
- wasd 分別對應鏡頭的 上,左,下,右 移動
- 鼠標移動到屏幕邊緣時, 鏡頭向對應方向卷動
- 滾動鼠標滾輪時, 視角拉近,拉遠
API
- 獲取鍵盤按鍵:
Input.GetKey("w")
- 獲取鼠標位置:
Input.mousePosition
- 獲取屏幕大小:
Screen.width/Screen.height
- 限制值的范圍:
Mathf.Clamp(value,min,max)
實際應用:
- 將場景的攝像機調節成 x增大 鏡頭左移, z增大 鏡頭上移, y增大 鏡頭拉遠. 并對攝像機添加腳本
CameraController
- 創建鏡頭滾動的配置參數: PanSpeed(鏡頭移動速度), ScrollSpeed(鏡頭深度變化速度)等
- 在Update()方法中 添加對應鍵盤,鼠標事件的監聽,并對保存的鏡頭position臨時變量賦值
- 確認position的邊界條件,再設置到鏡頭的Transform中
CameraController
using UnityEngine;
public class CameraController : MonoBehaviour
{
public float PanSpeed = 20f;
public float ScrollSpeed = 20f;
public float PanBoarderThiness = 100f;
public Vector2 PanLimit;
public float MinY = 20f;
public float MaxY = 100f;
void Update()
{
Vector3 pos = transform.position;
if (Input.GetKey("w") || MouseAtScreenTopEdge())
{
pos.z += PanSpeed * Time.deltaTime;
}
if (Input.GetKey("s") || MouseAtScreenBottomEdge())
{
pos.z -= PanSpeed * Time.deltaTime;
}
if (Input.GetKey("a") || MouseAtScreenLeftEdge())
{
pos.x -= PanSpeed * Time.deltaTime;
}
if (Input.GetKey("d") || MouseAtScreenRightEdge())
{
pos.x += PanSpeed * Time.deltaTime;
}
float scroll = Input.GetAxis("Mouse ScrollWheel");
pos.y += scroll * ScrollSpeed * Time.deltaTime;
pos.x = Mathf.Clamp(pos.x, -PanLimit.x, PanLimit.x);
pos.z = Mathf.Clamp(pos.z, -PanLimit.y, PanLimit.y);
pos.y = Mathf.Clamp(pos.y,MinY,MaxY);
transform.position = pos;
}
bool MouseAtScreenTopEdge()
{
return Input.mousePosition.y >= Screen.height - PanBoarderThiness && Input.mousePosition.y <= Screen.height;
}
bool MouseAtScreenBottomEdge()
{
return Input.mousePosition.y <= PanBoarderThiness && Input.mousePosition.y >= 0;
}
bool MouseAtScreenLeftEdge()
{
return Input.mousePosition.x <= PanBoarderThiness && Input.mousePosition.x >= 0;
}
bool MouseAtScreenRightEdge()
{
return Input.mousePosition.x >= Screen.width - PanBoarderThiness && Input.mousePosition.x <= Screen.width;
}
}