Unity中的Character Controller 简介
Slope Limit :坡度限制
Step Offset :每步偏移量
Skin Width :皮膚厚度
Min Move Distance :最小移動距離
Center :中心
Radius :半徑
Height :高度
Unity中可以使用character controller實現角色的控制,在unity中先創建一個需要被控制的角色,可以方塊體等,為主角加入CharacterController組件
創建C#腳本,寫入一下腳本
public Transform m_transform;
CharacterController m_ch;
void Start()
??? {
??????? m_transform = this.transform;
??????? m_ch = this.GetComponent<CharacterController>();
??? }
m_transfrom = this,transform; //的作用是獲取主角的transform組件
m_ch = this.GetComponent<CharacterController>();?
//的作用是獲取主角的characterController組件
繼續向腳本中添加代碼
??? float m_movSpeed = 5.0f;????? //移動速度
??? float m_rotSpeed = 1.0f;????? //旋轉速度
??? float m_jumphight = 3f;?????? //跳躍高度
??? float m_gravity = 9.8f;?????? //重力加速度
??? private Vector3 Velocity = Vector3.zero;???? //豎直方向上的一個向量
??? public Transform m_groundcheck;?? //與地面接觸的檢測器
??? public float m_checkradius = 0.2f;????? //地面檢測器的范圍
??? private bool m_isground;????????? //一個判斷是否與地面接觸的bool值,接觸則為true
public LayerMask layerMask;???? ???//地面層
這里提到了一個地面檢測器,地面檢測器的做法為在,主角的底部添加一個空的游戲體,調整一個合適的大小,盡量小一些
添加結束之后,我們在腳本中繼續添加如下代碼
void Update()
??? {
??????? m_isground = Physics.CheckSphere(m_groundcheck.position, m_checkradius, layerMask);
??????? if (m_isground && Velocity.y <0)
??????? {
??????????? Velocity.y = 0;
??????? }
??????? if (m_isground && Input.GetButtonDown("Jump"))
??????? {
??????????? Velocity.y += Mathf.Sqrt(m_jumphight * m_gravity);
??????? }
??????? //控制主角
??????? var vertical = Input.GetAxis("Vertical");? //鍵入ws
??????? var horizontal = Input.GetAxis("Horizontal"); //鍵入ad Horizontal
??????? var motion = transform.forward * vertical * m_movSpeed * Time.deltaTime;
??????? Velocity.y -= m_gravity * Time.deltaTime;??? //重力加速度 a += g*時間
??????? m_ch.Move(Velocity * Time.deltaTime);? //豎直方向的移動
??????? m_ch.Move(motion); //水平方向的移動
??????? m_transform.Rotate(Vector3.up,horizontal * m_rotSpeed);? //旋轉
}
m_isground = Physics.CheckSphere(m_groundcheck.position, m_checkradius, layerMask);這串代碼為一個觸碰檢測,如果檢測體m_groundcheck與layerMask接觸后則返回一個true
Velocity.y += Mathf.Sqrt(m_jumphight * m_gravity);
計算跳躍的近似公式
總結
以上是生活随笔為你收集整理的Unity中的Character Controller 简介的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 论文阅读|目标检测之CE-FPN,将通道
- 下一篇: VS2013各版本序列号