Files
godot-------/Script/Pawn/Player.cs
m0_75251201 7700703099 初次提交
2025-07-12 11:30:22 +08:00

141 lines
4.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Godot;
using System;
using System.Collections.Generic; // 使用 List 和 Dictionary 需要这个命名空间
namespace Cosmobox
{
public partial class Player : Pawn, IThing
{
// === 玩家属性 ===
[Export] public Camera2D PlayerCamera; // 玩家摄像机
[Export] public Sprite2D AimCursor; // 瞄准光标精灵
[Export] public Vector2 AimOffset = Vector2.Zero; // 瞄准点偏移量
public BagItemList bagItem = new();
public override void _Ready()
{
// 调用基类的_Ready方法
base._Ready();
// 尝试查找摄像机(如果未分配)
if (PlayerCamera == null)
{
PlayerCamera = GetViewport().GetCamera2D();
if (PlayerCamera == null)
{
GD.PrintErr("Player: 未分配摄像机且视口中没有活动摄像机!");
}
}
// 初始化瞄准光标
if (AimCursor != null)
{
AimCursor.Visible = true;
}
}
public void Update(double delta)
{
// 获取输入方向
Vector2 inputDirection = GetInputDirection();
// 处理移动调用Pawn基类方法
HandleMovement(inputDirection);
// 更新角色朝向(鼠标方向)
UpdateDirectionToMouse();
}
/// <summary>
/// 更新角色朝向鼠标方向
/// </summary>
private void UpdateDirectionToMouse()
{
if (PlayerCamera == null) return;
// 获取鼠标在游戏世界中的位置
Vector2 mousePosition = GetGlobalMousePosition();
// 计算从玩家位置到鼠标位置的方向向量
Vector2 directionToMouse = (mousePosition - GlobalPosition).Normalized();
// 调用基类方法更新视觉方向
UpdateDirection(directionToMouse);
}
/// <summary>
/// 更新瞄准光标位置
/// </summary>
private void UpdateAimCursor()
{
if (AimCursor == null || PlayerCamera == null) return;
// 获取鼠标位置
Vector2 mousePosition = GetGlobalMousePosition();
// 设置光标位置(带偏移)
AimCursor.GlobalPosition = mousePosition + AimOffset;
}
/// <summary>
/// 获取键盘输入方向
/// </summary>
/// <returns>归一化的移动方向向量</returns>
private Vector2 GetInputDirection()
{
Vector2 direction = Vector2.Zero;
// 处理上下左右输入(确保项目设置中已配置这些输入)
if (Input.IsActionPressed("ui_up"))
{
direction.Y -= 1; // 上移
}
if (Input.IsActionPressed("ui_down"))
{
direction.Y += 1; // 下移
}
if (Input.IsActionPressed("ui_left"))
{
direction.X -= 1; // 左移
}
if (Input.IsActionPressed("ui_right"))
{
direction.X += 1; // 右移
}
return direction.Normalized(); // 确保斜向移动速度一致
}
/// <summary>
/// 获取瞄准方向(从玩家指向鼠标位置)
/// </summary>
public Vector2 GetAimDirection()
{
if (PlayerCamera == null) return Vector2.Zero;
Vector2 mousePosition = GetGlobalMousePosition();
return (mousePosition - GlobalPosition).Normalized();
}
/// <summary>
/// 获取瞄准角度(弧度)
/// </summary>
public float GetAimAngle()
{
Vector2 aimDir = GetAimDirection();
return Mathf.Atan2(aimDir.Y, aimDir.X);
}
/// <summary>
/// 获取瞄准角度(度)
/// </summary>
public float GetAimAngleDegrees()
{
return Mathf.RadToDeg(GetAimAngle());
}
}
}