Unity中的Character Controller 简介
Slope Limit :坡度限制
Step Offset :每步偏移量
Skin Width :皮膚厚度
Min Move Distance :最小移動(dòng)距離
Center :中心
Radius :半徑
Height :高度
Unity中可以使用character controller實(shí)現(xiàn)角色的控制,在unity中先創(chuàng)建一個(gè)需要被控制的角色,可以方塊體等,為主角加入CharacterController組件
創(chuàng)建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組件
繼續(xù)向腳本中添加代碼
??? float m_movSpeed = 5.0f;????? //移動(dòng)速度
??? float m_rotSpeed = 1.0f;????? //旋轉(zhuǎn)速度
??? float m_jumphight = 3f;?????? //跳躍高度
??? float m_gravity = 9.8f;?????? //重力加速度
??? private Vector3 Velocity = Vector3.zero;???? //豎直方向上的一個(gè)向量
??? public Transform m_groundcheck;?? //與地面接觸的檢測(cè)器
??? public float m_checkradius = 0.2f;????? //地面檢測(cè)器的范圍
??? private bool m_isground;????????? //一個(gè)判斷是否與地面接觸的bool值,接觸則為true
public LayerMask layerMask;???? ???//地面層
這里提到了一個(gè)地面檢測(cè)器,地面檢測(cè)器的做法為在,主角的底部添加一個(gè)空的游戲體,調(diào)整一個(gè)合適的大小,盡量小一些
添加結(jié)束之后,我們?cè)谀_本中繼續(xù)添加如下代碼
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*時(shí)間
??????? m_ch.Move(Velocity * Time.deltaTime);? //豎直方向的移動(dòng)
??????? m_ch.Move(motion); //水平方向的移動(dòng)
??????? m_transform.Rotate(Vector3.up,horizontal * m_rotSpeed);? //旋轉(zhuǎn)
}
m_isground = Physics.CheckSphere(m_groundcheck.position, m_checkradius, layerMask);這串代碼為一個(gè)觸碰檢測(cè),如果檢測(cè)體m_groundcheck與layerMask接觸后則返回一個(gè)true
Velocity.y += Mathf.Sqrt(m_jumphight * m_gravity);
計(jì)算跳躍的近似公式
總結(jié)
以上是生活随笔為你收集整理的Unity中的Character Controller 简介的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 论文阅读|目标检测之CE-FPN,将通道
- 下一篇: VS2013各版本序列号