Unity3D控制人物移动跳跃
发表于2017-11-30
在Unity3D中控制人物移动的方法很多,可以使用transform.Translate方法,但为了不穿越其他物体,需要使用刚体rigidbody。还可以使用角色控制器,角色控制器是自带刚体Rigidbody和碰撞器Collider的,移动可以使用CharacterController组件。
在使用CharacterController组件实现跳跃时,需要检测人物是否在地面上,CharacterController提供了属性isGrounded以供检测,但是在使用中发现isGrounded总是返回false,个人认为CharacterController的SkinWidth要设置合理,官方推荐是radius的0.1大小,然后去监测或者使用isGrounded属性是在FixedUpdate里面而不是在Update里面,两者的结果会大不相同,这里替代使用射线检测方法来判断是否着地,射线检测其实就是用从人物身体发射一条向下的射线判断射线在给定距离内是否碰撞物体即可以判断是否着地。
代码如下:
public float speed = 1; public float jumpSpeed = 10; public float gravity = 20; public float margin = 0.1f; private Vector3 moveDirection = Vector3.zero; // 通过射线检测主角是否落在地面或者物体上 bool IsGrounded() { return Physics.Raycast(transform.position, -Vector3.up, margin); } // Update is called once per frame void Update () { // 控制移动 float h = Input.GetAxis ("Horizontal"); float v = Input.GetAxis ("Vertical"); if (IsGrounded()) { moveDirection = new Vector3 (h, 0, v); moveDirection = transform.TransformDirection (moveDirection); moveDirection *= speed; // 空格键控制跳跃 if (Input.GetButton ("Jump")) { moveDirection.y = jumpSpeed; } } moveDirection.y -= gravity * Time.deltaTime; controller.Move (moveDirection * Time.deltaTime); }