63 lines
2.6 KiB
C#
63 lines
2.6 KiB
C#
using Godot;
|
||
|
||
namespace Milimoe.GodotGame
|
||
{
|
||
public partial class CharacterBody : CharacterBody2D
|
||
{
|
||
/// <summary>
|
||
/// 移动速度 (像素/秒)
|
||
/// </summary>
|
||
[Export]
|
||
public float Speed = 200.0f;
|
||
|
||
/// <summary>
|
||
/// _PhysicsProcess 是 Godot 进行物理计算和运动更新的函数
|
||
/// </summary>
|
||
/// <param name="delta"></param>
|
||
public override void _PhysicsProcess(double delta)
|
||
{
|
||
// --- 1. 获取输入向量 ---
|
||
// 获取水平输入轴的值 (-1 到 1)
|
||
float inputX = Input.GetAxis("move_left", "move_right");
|
||
// 获取垂直输入轴的值 (-1 到 1)
|
||
// 你需要在项目设置 -> Input Map 中设置 "move_up" 和 "move_down" 动作,
|
||
// 并绑定相应的按键(如 W/上箭头 和 S/下箭头)。
|
||
float inputY = Input.GetAxis("move_up", "move_down");
|
||
|
||
// 创建一个表示输入方向的向量
|
||
Vector2 inputVector = new Vector2(inputX, inputY);
|
||
|
||
// --- 2. 计算目标速度 ---
|
||
Vector2 targetVelocity;
|
||
|
||
// 检查是否有输入
|
||
if (inputVector.LengthSquared() > 0) // 使用 LengthSquared() 比 Length() 性能稍好,只需要判断是否大于0
|
||
{
|
||
// 如果有输入,将输入向量标准化 (避免对角线移动过快)
|
||
// 然后乘以速度得到目标速度
|
||
targetVelocity = inputVector.Normalized() * Speed;
|
||
}
|
||
else
|
||
{
|
||
// 如果没有输入,目标速度为零 (停止)
|
||
targetVelocity = Vector2.Zero;
|
||
}
|
||
|
||
// --- 3. 平滑过渡到目标速度 ---
|
||
// 使用 Mathf.MoveToward 平滑地改变当前速度到目标速度
|
||
// 这样角色移动和停止会更平滑,而不是瞬间加速/停止
|
||
// 这里的 Speed 用作最大步长,确保在1秒内能达到最大速度(如果 delta 累积到1)
|
||
Velocity = Velocity.MoveToward(targetVelocity, Speed * (float)delta);
|
||
|
||
// --- 4. 调用 MoveAndSlide() ---
|
||
// 这是关键步骤!它会根据当前的 Velocity 向量移动 CharacterBody2D,
|
||
// 并自动处理与场景中其他碰撞体的碰撞。
|
||
// 在俯视角游戏中,MoveAndSlide() 会处理与墙壁、障碍物等的碰撞,阻止角色穿过它们。
|
||
MoveAndSlide();
|
||
|
||
// --- 5. (可选) 其他逻辑 ---
|
||
// 你可以在这里添加其他逻辑,比如播放动画、处理交互等。
|
||
}
|
||
}
|
||
}
|