第一步:在场景中创建一个平面以及胶囊体
第二步:给胶囊体加上CharacterController角色控制器组件
第三步:创建一个实现移动的脚本,名字自定义
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
private CharacterController player_Cha;//角色控制器、
[SerializeField]
private float moveSpeed = 5;//角色移动速度
private Vector3 player_Vec;//存储位移方向向量
private float gravity = 9.8f;//重力加速度
private void Start()
{
player_Cha = GetComponent<CharacterController>();//获取CharacterController组件
}
private void FixedUpdate()
{
Player_Move();
}
//角色移动
public void Player_Move()
{
if(player_Cha.isGrounded)//如果角色触地
{
float h = Input.GetAxis("Horizontal");//获取水平移动输入值
float v = Input.GetAxis("Vertical");//获取垂直移动输入值
player_Vec.x = h * moveSpeed*Time.deltaTime;
player_Vec.z = v * moveSpeed * Time.deltaTime;
this.transform.TransformDirection(player_Vec);//本地坐标转世界坐标
}
player_Vec.y-=gravity*moveSpeed*Time.deltaTime;//模拟重力实现
player_Cha.Move(player_Vec);//实现移动
}
}
这里面放在FixedUpdate是保证移动的稳定性;SerializeField特性能将私有变量在控制面板上也能像公开变量一样使用;TransformDirection()是将本地坐标转为世界坐标,方便人物加上鼠标控制旋转以后可以向人物当前朝向前进或后退等。关于Horizontal和Vertical新手不明白的可以去搜一下。