- 创建Unity项目并设置场景
打开Unity并创建一个新的3D项目。
在项目视图中,右键点击并选择 Create > 3D Object > Plane 来创建一个平面作为地面。
右键点击 Create > 3D Object > Capsule 创建一个胶囊体,作为玩家角色,并将其命名为“Player”。
将Player对象稍微提升,使其在地面之上(例如:设置Transform组件中的Position为(0, 1, 0))。
添加 CharacterController 组件到Player对象(在Inspector面板中点击 Add Component > CharacterController)。
- 创建脚本控制角色移动
在项目视图中,右键点击并选择 Create > C# Script 创建一个新的C#脚本,命名为 PlayerMovement。
将脚本拖动到Player对象上,以附加该脚本到Player对象。
双击 PlayerMovement 脚本打开Visual Studio或其他代码编辑器,并输入以下代码:
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private CharacterController controller;
private Vector3 playerVelocity;
private bool groundedPlayer;
public float playerSpeed = 2.0f;
public float jumpHeight = 1.0f;
public float gravityValue = -9.81f;
private void Start()
{
controller = gameObject.GetComponent<CharacterController>();
}
void Update()
{
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
controller.Move(move * Time.deltaTime * playerSpeed);
// 改变角色的高度位置
if (move != Vector3.zero)
{
gameObject.transform.forward = move;
}
// 跳跃逻辑
if (Input.GetButtonDown("Jump") && groundedPlayer)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
}
- 解释和测试
变量声明:
controller: 存储 CharacterController 组件。
playerVelocity: 用于处理角色的当前速度。
groundedPlayer: 检查角色是否在地面上。
playerSpeed: 控制角色的移动速度。
jumpHeight: 控制角色跳跃的高度。
gravityValue: 控制重力的影响。
Start() 方法:
初始化 CharacterController 组件。
Update() 方法:
检查角色是否在地面上,并重置垂直速度。
获取玩家输入的移动方向,并通过 controller.Move 实现移动。
设置角色面向移动方向。
处理跳跃逻辑,使用物理公式计算跳跃速度。
应用重力影响到角色,并通过 controller.Move 更新角色位置。
保存脚本并返回Unity,点击播放按钮测试角色的移动和跳跃功能。使用WASD键进行前后左右移动,空格键进行跳跃。