首先是角色控制器的添加 选定模型对象 在其Inspector视图中选择Add Component -> Physics -> Character Controller 出现组建如下图
此时模型对象上会出现一个胶囊体,通过改变Center、Radius以及Hight的值来调整胶囊体的位置,使之恰好包裹住模型对象,如下图
点击运行会发现狼人穿过地面下落,这是因为现在模型对象已经受物理重力影响,而地面未添加刚体属性造成的,故点选地面对象 Add Component -> Physics -> RightBody 添加刚体,同时锁定地面的几个轴向防止撞击后位移
接下来我们将利用脚本控制游戏对象如何在跑道上以一定的速度奔跑
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | using UnityEngine; using System.Collections; public class MoveManger : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { //这里获取Gameobject上的controler组件 CharacterController controller = GetComponent("CharacterController") as CharacterController; //游戏对象旋转 Input.GetAxis("Horizontal") 意为读取键盘输入 这里仅Y轴旋转 transform.Rotate(0, Input.GetAxis("Horizontal") * 3.0f, 0); //定义前进方向向量 Vector3 forward = transform.TransformDirection(Vector3.forward); //获取键盘输入信息即前进后退 float curSpeed = 10.0f * Input.GetAxis("Vertical"); //对象简单移动 按照前进方向 controller.SimpleMove(forward * curSpeed); } } |
将以上脚本绑定至添加了角色控制组件的游戏对象上,点击运行游戏,使用键盘的方向键或WASD即可操纵游戏对象移动
如图:
同时我们看一下更复杂的移动方式,即CharacterController.Move 移动,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | using UnityEngine; using System.Collections; public class MoveManger : MonoBehaviour { //新建一个空向量 private Vector3 moveDirection = Vector3.zero; // Use this for initialization void Start () { } // Update is called once per frame void Update () { //这里获取Gameobject上的controler组件 CharacterController controller = GetComponent("CharacterController") as CharacterController; //判断是否着地 if (controller.isGrounded) { //游戏前后及横向移动 moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); moveDirection = transform.TransformDirection(moveDirection); moveDirection *= 6.0f; //判断是否按下跳起键 if (Input.GetButton("Jump")) { moveDirection.y = 4.0f; } } //应用重力。 moveDirection.y -= 20.0f * Time.deltaTime; //移动控制器。 controller.Move(moveDirection * Time.deltaTime); } |
此时游戏对象带有了重力属性,移动类似CS的横向及前后移动,此时在添加读取鼠标移动来转动角色对象即可实现CS的行动模拟。
通过改变向量变化的速度值,我们可以实现奔跑的加速及减速功能,如果是竞速游戏的话可以添加一个全局脚本,来对各个游戏对象的速度值进行宏观的调控。
本文先写到这里,一些拓展大家自己可以举一反三。谢谢关注。
BeiTown
2013.03.07