unity通用角色控制脚本走跑,idleidle
时间: 2023-06-10 17:08:42 浏览: 63
以下是一个适用于Unity的通用角色控制脚本,包括走、跑和站立等状态的控制:
```csharp
using UnityEngine;
public class CharacterController : MonoBehaviour
{
public float walkSpeed = 5.0f; // 行走速度
public float runSpeed = 10.0f; // 跑步速度
public float gravity = 20.0f; // 重力值
public float jumpHeight = 2.0f; // 跳跃高度
private Vector3 moveDirection = Vector3.zero; // 移动方向
private bool isRunning = false; // 是否正在跑步
private bool isJumping = false; // 是否正在跳跃
private CharacterController controller; // 角色控制器
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
if (controller.isGrounded) // 如果角色在地面上
{
float moveSpeed = isRunning ? runSpeed : walkSpeed; // 根据是否跑步选择移动速度
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); // 获取移动方向
moveDirection *= moveSpeed; // 根据移动速度调整移动方向
if (Input.GetButton("Jump")) // 如果按下跳跃键
{
moveDirection.y = Mathf.Sqrt(2 * jumpHeight * gravity); // 计算跳跃速度
isJumping = true; // 标记正在跳跃
}
}
moveDirection.y -= gravity * Time.deltaTime; // 根据重力调整移动方向
controller.Move(moveDirection * Time.deltaTime); // 移动角色
if (controller.isGrounded && isJumping) // 如果角色跳跃完毕
{
isJumping = false; // 标记结束跳跃
}
}
void OnGUI()
{
if (isRunning) // 显示当前状态
{
GUI.Label(new Rect(10, 10, 100, 20), "Running");
}
else if (moveDirection.magnitude > 0) // 如果在行走
{
GUI.Label(new Rect(10, 10, 100, 20), "Walking");
}
else // 否则,处于空闲状态
{
GUI.Label(new Rect(10, 10, 100, 20), "Idle");
}
}
public void SetRunning(bool running) // 设置是否跑步
{
isRunning = running;
}
}
```
使用方法:
1. 将脚本添加到角色对象上;
2. 在Inspector面板中设置行走速度、跑步速度、重力值和跳跃高度等参数;
3. 在输入管理器中设置水平和垂直轴的名称(默认为“Horizontal”和“Vertical”);
4. 在按键管理器中设置跳跃键的名称(默认为“Jump”);
5. 在其他脚本中调用 `SetRunning(true)` 方法即可让角色开始跑步。默认为走路状态。