這是操作頁面

腳本如下
public class Player : MonoBehaviour {
private CharacterController m_ch; // 玩家角色控制器
public Transform m_transform; // 玩家實體
private float m_movSpeed = 10.0f; // 玩家移動基速
public int m_life = 5; // 生命值
private float m_gravity = 3.0f; // 重力
private Transform m_camTransform; // 攝像機
private Vector3 m_camRot; // 攝像機姿勢-旋轉角度
private float m_camHeight = 4.5f; // 攝像機高度-玩家的眼睛
void Start()
{
m_transform = this.transform; // 本角色實體
m_ch = this.GetComponent<CharacterController>(); // 本角色的控制器
m_camTransform = Camera.main.transform;// 獲取攝像機
/** 設定攝像機初始位置 **/
Vector3 pos = m_transform.position; // 玩家位置
pos.y += m_camHeight; // 鏡頭高度
m_camTransform.position = pos; // 初始化初始攝像機位置
m_camTransform.rotation = m_transform.rotation; // 初始化攝像機姿勢
/**
* eulerAngles的三個變數 z,x,y 表示三個繞坐標軸旋轉的角度(世界坐標軸)
* 順序是z,x,y。如果角度超過360的話,要用Rotate來代替,用四元數來旋轉
* 這三個x,y,z的值對應Inspector上的transform/Rotation的三個值
* 所繞角度是順著坐標軸看,按逆時針旋轉的角度
**/
m_camRot = m_camTransform.eulerAngles; // 存盤攝像機姿勢
Screen.lockCursor = true; // 鎖定滑鼠
}
void Update()
{
if (m_life <= 0) return; // 如果生命為0,什么也不做
/**
* Input.GetAxis(string name);
* 根據坐標軸名稱回傳虛擬坐標系中的值。回傳值型別:float
* 引數:Horizontal, Vertial, Mouse X, Mouse Y
* 其中Horizontal, Vertical 默認對應小鍵盤上的左右、上下鍵,回傳值為-1或1
* Mouse X, Mouse Y 對應滑鼠位置,回傳值不定
* 以上都是在<a class="relatedlink" href="http://www.unitymanual.com/" target="_blank">unity3d</a>中預定義好的映射,可以通過 Edit->Project Settings->Input 來重新定義映射
**/
float rv = Input.GetAxis("Mouse Y"); // 滑鼠 Y 軸移動距離,抬頭角度
float rh = Input.GetAxis("Mouse X"); // 滑鼠 X 軸移動距離,轉身角度
m_camRot.x -= rv; // X軸 攝像機仰角-抬頭
m_camRot.y += rh; // Y軸 攝像機旋轉
m_camTransform.eulerAngles = m_camRot; // 攝像機姿勢修正
// 使主角的面向方向與攝像機一致
Vector3 camrot = m_camTransform.eulerAngles; // 提取攝像機姿勢
camrot.x = 0; camrot.z = 0; // 防止后退
m_transform.eulerAngles = camrot; // 玩家姿勢修正
float xm = 0, ym = 0, zm = 0;
// 重力運動
ym -= m_gravity * Time.deltaTime * 10;
// 前進/后退
if (Input.GetKey(KeyCode.W))
zm += m_movSpeed * Time.deltaTime * 3;
else if (Input.GetKey(KeyCode.S))
zm -= m_movSpeed * Time.deltaTime * 3;
// 左移/右移
if (Input.GetKey(KeyCode.A))
xm -= m_movSpeed * Time.deltaTime * 3;
else if (Input.GetKey(KeyCode.D))
xm += m_movSpeed * Time.deltaTime * 3;
// 移動
m_ch.Move(m_transform.TransformDirection(new Vector3(xm, ym, zm)));
// 使攝像機的位置與主角一致
Vector3 pos = m_transform.position;
pos.y += m_camHeight;
m_camTransform.position = pos;
}
void OnDrawGizmos()
{
Gizmos.DrawIcon(transform.position, "pfsPlayer.png", true);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/17287.html
標籤:Unity3D
上一篇:歐拉角
