Supports the use of mouse wheel to switch currently held items.

支持使用鼠标滚轮切换当前持有的物品了。
This commit is contained in:
Cold-Mint 2024-05-04 22:59:46 +08:00
parent b7939af5d0
commit 801b3dd93b
Signed by: Cold-Mint
GPG Key ID: C5A9BF8A98E0CE99
10 changed files with 622 additions and 480 deletions

View File

@ -133,11 +133,6 @@ hotbar_9={
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":57,"physical_keycode":0,"key_label":0,"unicode":57,"echo":false,"script":null)
]
}
hotbar_10={
"deadzone": 0.5,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":48,"physical_keycode":0,"key_label":0,"unicode":48,"echo":false,"script":null)
]
}
hotbar_next={
"deadzone": 0.5,
"events": [Object(InputEventMouseButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"button_mask":16,"position":Vector2(241, 17),"global_position":Vector2(245, 58),"factor":1.0,"button_index":5,"canceled":false,"pressed":true,"double_click":false,"script":null)

View File

@ -90,7 +90,7 @@ public static class Config
/// <para>How many item slots are there on the shortcut bar</para>
/// <para>快捷栏上有多少个物品槽</para>
/// </summary>
public const int HotBarSize = 10;
public const int HotBarSize = 9;
/// <summary>

View File

@ -13,7 +13,7 @@ public class GameSceneNodeHolder
/// <para>Player instances within the game scene</para>
/// <para>游戏场景内的玩家实例</para>
/// </summary>
public static Player Player { get; set; }
public static Player? Player { get; set; }
/// <summary>
/// <para>WeaponContainer</para>

View File

@ -2,7 +2,6 @@ using System;
using System.Collections.Generic;
using ColdMint.scripts.camp;
using ColdMint.scripts.damage;
using ColdMint.scripts.debug;
using ColdMint.scripts.health;
using ColdMint.scripts.weapon;
using Godot;
@ -20,44 +19,50 @@ namespace ColdMint.scripts.character;
public partial class CharacterTemplate : CharacterBody2D
{
// Get the gravity from the project settings to be synced with RigidBody nodes.
public float gravity = ProjectSettings.GetSetting("physics/2d/default_gravity").AsSingle();
public const float Speed = 300.0f;
// 从项目设置中获取与RigidBody节点同步的重力。
protected float Gravity = ProjectSettings.GetSetting("physics/2d/default_gravity").AsSingle();
protected const float Speed = 300.0f;
public const float JumpVelocity = -240;
protected const float JumpVelocity = -240;
protected string _characterName;
public string? ReadOnlyCharacterName => CharacterName;
public string CharacterName => _characterName;
protected string? CharacterName;
//Items currently held
//当前持有的物品
public Node2D CurrentItem;
public Node2D? CurrentItem;
//Define a pick up range
//定义一个拾起范围
private Area2D PickingArea;
private Area2D? _pickingArea;
protected AnimatedSprite2D AnimatedSprite2D;
private AnimatedSprite2D? _animatedSprite2D;
//一个标志,定义物品的位置
protected Marker2D ItemMarker2D;
//A marker that defines the location of the item
//一个标记,定义物品的位置
protected Marker2D? ItemMarker2D;
//The original X-coordinate of the item marker
//物品标记的原始X坐标
private float ItemMarkerOriginalX;
private float _itemMarkerOriginalX;
public float ReadOnlyItemMarkerOriginalX => ItemMarkerOriginalX;
protected float ReadOnlyItemMarkerOriginalX => _itemMarkerOriginalX;
//Face left?
//面向左边吗
public bool FacingLeft = false;
//The force added by the AddForce method
//由AddForce方法追加的力
private Vector2 additionalForce = Vector2.Zero;
private Vector2 _additionalForce = Vector2.Zero;
protected int CurrentHp;
//The initial health of the character after creation
//角色创建后的初始血量
private int InitialHp;
private int _initialHp;
protected int MaxHp;
@ -65,20 +70,20 @@ public partial class CharacterTemplate : CharacterBody2D
/// <para>The camp ID of the role</para>
/// <para>角色的阵营ID</para>
/// </summary>
public string CampId;
public string CampId = null!;
private DamageNumberNodeSpawn DamageNumber;
private DamageNumberNodeSpawn? _damageNumber;
private HealthBar _healthBar;
private HealthBar? _healthBar;
private DateTime _lastDamageTime;
/// <summary>
/// <para>Pick up all items within range</para>
/// <para>拾捡范围内的所有物品</para>
/// </summary>
private List<Node> _pickingRangeBodies;
private List<Node>? _pickingRangeBodies;
public Node[] PickingRangeBodies => _pickingRangeBodies.ToArray();
public Node[] PickingRangeBodies => _pickingRangeBodies?.ToArray() ?? Array.Empty<Node>();
/// <summary>
@ -107,23 +112,26 @@ public partial class CharacterTemplate : CharacterBody2D
{
base._Ready();
_pickingRangeBodies = new List<Node>();
_characterName = GetMeta("Name", Name).AsString();
CharacterName = GetMeta("Name", Name).AsString();
CampId = GetMeta("CampId", Config.CampId.Default).AsString();
MaxHp = GetMeta("MaxHp", Config.DefaultMaxHp).AsInt32();
if (MaxHp <= 0)
{
//If Max blood volume is 0 or less, set Max blood volume to 10
//若最大血量为0或小于0则将最大血量设置为10
MaxHp = Config.DefaultMaxHp;
}
InitialHp = GetMeta("InitialHp", "0").AsInt32();
if (InitialHp <= 0)
_initialHp = GetMeta("InitialHp", "0").AsInt32();
if (_initialHp <= 0)
{
//If the initial blood volume is less than or equal to 0, the initial blood volume is set to the maximum blood volume
//若初始血量小于等于0则将初始血量设置为最大血量
InitialHp = MaxHp;
_initialHp = MaxHp;
}
CurrentHp = InitialHp;
CurrentHp = _initialHp;
//The health bar of a creature may be null.
//生物的健康条可能为null。
_healthBar = GetNodeOrNull<HealthBar>("HealthBar");
if (_healthBar != null)
@ -133,19 +141,20 @@ public partial class CharacterTemplate : CharacterBody2D
ItemMarker2D = GetNode<Marker2D>("ItemMarker2D");
ItemMarkerOriginalX = ItemMarker2D.Position.X;
AnimatedSprite2D = GetNode<AnimatedSprite2D>("AnimatedSprite2D");
PickingArea = GetNode<Area2D>("Area2DPickingArea");
DamageNumber = GetNode<Marker2D>("DamageNumber") as DamageNumberNodeSpawn;
if (PickingArea != null)
_itemMarkerOriginalX = ItemMarker2D.Position.X;
_animatedSprite2D = GetNode<AnimatedSprite2D>("AnimatedSprite2D");
_pickingArea = GetNode<Area2D>("Area2DPickingArea");
_damageNumber = GetNode<Marker2D>("DamageNumber") as DamageNumberNodeSpawn;
if (_pickingArea != null)
{
//If true, the zone will detect objects or areas entering and leaving the zone.
//如果为true该区域将检测进出该区域的物体或区域。
PickingArea.Monitoring = true;
_pickingArea.Monitoring = true;
//Other regions cannot detect our pick region
//其他区域不能检测到我们的拾取区域
PickingArea.Monitorable = false;
PickingArea.BodyEntered += EnterThePickingRangeBody;
PickingArea.BodyExited += ExitThePickingRangeBody;
_pickingArea.Monitorable = false;
_pickingArea.BodyEntered += EnterThePickingRangeBody;
_pickingArea.BodyExited += ExitThePickingRangeBody;
}
}
@ -160,11 +169,6 @@ public partial class CharacterTemplate : CharacterBody2D
/// </returns>
public bool PickItem(Node2D pickAbleItem)
{
if (pickAbleItem == null)
{
return false;
}
if (CurrentItem == null)
{
if (pickAbleItem is WeaponTemplate weaponTemplate)
@ -190,6 +194,7 @@ public partial class CharacterTemplate : CharacterBody2D
return false;
}
/// <summary>
/// <para>Use what you have in your hand</para>
/// <para>使用手中的物品</para>
@ -213,6 +218,7 @@ public partial class CharacterTemplate : CharacterBody2D
{
base._Process(delta);
//If the time difference between the last injury and the current time is greater than the time displayed in the health bar, the health bar is hidden
//如果上次受到伤害的时间与当前时间的时间差大于健康条显示时间,则隐藏健康条
var timeSpan = DateTime.Now - _lastDamageTime;
if (timeSpan > Config.HealthBarDisplaysTime)
@ -228,7 +234,7 @@ public partial class CharacterTemplate : CharacterBody2D
/// <para>Update the role's health bar</para>
/// <para>更新角色的健康条</para>
/// </summary>
protected void UpDataHealthBar(DamageTemplate damageTemplate)
private void UpDataHealthBar(DamageTemplate damageTemplate)
{
if (_healthBar == null)
{
@ -287,11 +293,12 @@ public partial class CharacterTemplate : CharacterBody2D
public bool Damage(DamageTemplate damageTemplate)
{
_lastDamageTime = DateTime.Now;
DamageNumber.Display(damageTemplate);
_damageNumber?.Display(damageTemplate);
CurrentHp -= damageTemplate.Damage;
OnHit(damageTemplate);
if (CurrentHp <= 0)
{
//Character death
//角色死亡
OnDie(damageTemplate);
return true;
@ -308,7 +315,7 @@ public partial class CharacterTemplate : CharacterBody2D
/// <param name="force"></param>
public void AddForce(Vector2 force)
{
additionalForce = force;
_additionalForce = force;
}
protected virtual void OnHit(DamageTemplate damageTemplate)
@ -332,7 +339,7 @@ public partial class CharacterTemplate : CharacterBody2D
/// <param name="node"></param>
protected virtual void EnterThePickingRangeBody(Node node)
{
_pickingRangeBodies.Add(node);
_pickingRangeBodies?.Add(node);
}
/// <summary>
@ -342,7 +349,7 @@ public partial class CharacterTemplate : CharacterBody2D
/// <param name="node"></param>
protected virtual void ExitThePickingRangeBody(Node node)
{
_pickingRangeBodies.Remove(node);
_pickingRangeBodies?.Remove(node);
}
/// <summary>
@ -351,7 +358,12 @@ public partial class CharacterTemplate : CharacterBody2D
/// </summary>
protected virtual void Flip()
{
AnimatedSprite2D.FlipH = FacingLeft;
if (_animatedSprite2D == null)
{
return;
}
_animatedSprite2D.FlipH = FacingLeft;
}
@ -368,12 +380,12 @@ public partial class CharacterTemplate : CharacterBody2D
// Add the gravity.
//增加重力。
if (!IsOnFloor())
velocity.Y += gravity * (float)delta;
velocity.Y += Gravity * (float)delta;
// The ref keyword passes its pointer to the following method so that it can be modified in the method.
// ref关键字将其指针传递给下面的方法以便在方法中修改它。
HookPhysicsProcess(ref velocity, delta);
Velocity = velocity + additionalForce;
additionalForce = Vector2.Zero;
Velocity = velocity + _additionalForce;
_additionalForce = Vector2.Zero;
MoveAndSlide();
}
@ -390,6 +402,7 @@ public partial class CharacterTemplate : CharacterBody2D
return;
}
// Apply the rotation Angle to the node
// 将旋转角度应用于节点
CurrentItem.LookAt(position);
}

View File

@ -7,6 +7,7 @@ using System.Threading.Tasks;
using ColdMint.scripts;
using ColdMint.scripts.character;
using ColdMint.scripts.damage;
using ColdMint.scripts.debug;
using ColdMint.scripts.utils;
using ColdMint.scripts.weapon;
@ -51,7 +52,7 @@ public partial class Player : CharacterTemplate
public override void _Ready()
{
base._Ready();
_characterName = TranslationServer.Translate("default_player_name");
CharacterName = TranslationServer.Translate("default_player_name");
FloatLabelPackedScene = GD.Load<PackedScene>("res://prefab/ui/FloatLabel.tscn");
Parabola = GetNode<Line2D>("Parabola");
PlatformDetectionRayCast2D = GetNode<RayCast2D>("PlatformDetectionRayCast");
@ -203,6 +204,7 @@ public partial class Player : CharacterTemplate
{
GameSceneNodeHolder.HotBar.AddItem(weaponTemplate);
}
PickAbleItem = null;
TotalNumberOfPickups--;
if (FloatLabel != null)
@ -241,7 +243,7 @@ public partial class Player : CharacterTemplate
if (CurrentItem != null)
{
Parabola.Points =
ParabolicUtils.ComputeParabolic(ItemMarker2D.Position, GetThrowVelocity(), gravity, 0.1f);
ParabolicUtils.ComputeParabolic(ItemMarker2D.Position, GetThrowVelocity(), Gravity, 0.1f);
}
}
@ -284,13 +286,13 @@ public partial class Player : CharacterTemplate
CurrentItem = null;
TotalNumberOfPickups++;
GameSceneNodeHolder.HotBar.RemoveItemFromItemSlotBySelectIndex(1);
UpdateOperationTip();
}
}
}
private Vector2 GetThrowVelocity()
{
//我们拿到鼠标的位置,将其归一化处理,然后乘以玩家可扔出的距离
@ -373,7 +375,7 @@ public partial class Player : CharacterTemplate
{
if (weapon.Owner is CharacterTemplate characterTemplate)
{
stringBuilder.Append(characterTemplate.CharacterName);
stringBuilder.Append(characterTemplate.ReadOnlyCharacterName);
stringBuilder.Append(TranslationServer.Translate("de"));
}
}

View File

@ -1,10 +1,15 @@
using System.Collections.Generic;
using System.Linq;
using ColdMint.scripts.debug;
using ColdMint.scripts.weapon;
using Godot;
namespace ColdMint.scripts.inventory;
/// <summary>
/// <para>HotBar</para>
/// <para>快捷物品栏</para>
/// </summary>
public partial class HotBar : HBoxContainer
{
private PackedScene _itemSlotPackedScene;
@ -25,6 +30,13 @@ public partial class HotBar : HBoxContainer
public override void _Process(double delta)
{
base._Process(delta);
if (Input.IsActionPressed("throw"))
{
//Players are not allowed to switch current items while throwing them.
//玩家在抛物品时禁止切换当前物品。
return;
}
if (Input.IsActionJustPressed("hotbar_next"))
{
var count = _itemSlotNodes.Count;
@ -32,6 +44,7 @@ public partial class HotBar : HBoxContainer
{
return;
}
//Mouse wheel down
//鼠标滚轮向下
var oldSelectIndex = selectIndex;
@ -51,6 +64,7 @@ public partial class HotBar : HBoxContainer
{
return;
}
//Mouse wheel up
//鼠标滚轮向上
var oldSelectIndex = selectIndex;
@ -107,11 +121,6 @@ public partial class HotBar : HBoxContainer
{
SelectItemSlotByHotBarShortcutKey(8);
}
if (Input.IsActionJustPressed("hotbar_10"))
{
SelectItemSlotByHotBarShortcutKey(9);
}
}
/// <summary>
@ -136,6 +145,41 @@ public partial class HotBar : HBoxContainer
selectIndex = newIndex;
}
/// <summary>
/// <para>Removes an item from the currently selected inventory</para>
/// <para>移除当前选中的物品栏内的物品</para>
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
public bool RemoveItemFromItemSlotBySelectIndex(int number)
{
return RemoveItemFromItemSlot(selectIndex, number);
}
/// <summary>
/// <para>Remove items from the item slot</para>
/// <para>从物品槽内移除物品</para>
/// </summary>
/// <param name="itemSlotIndex">
///<para>When this number is greater than the number of item slots, residual filtering is used.</para>
///<para>当此数量大于物品槽的数量时,会使用余数筛选。</para>
/// </param>
public bool RemoveItemFromItemSlot(int itemSlotIndex, int number)
{
var count = _itemSlotNodes.Count;
if (count == 0)
{
//Prevents the dividend from being 0
//防止被除数为0
return false;
}
var newIndex = itemSlotIndex % count;
var itemSlot = _itemSlotNodes[newIndex];
return itemSlot.RemoveItem(number);
}
/// <summary>
/// <para>Select an item slot</para>
/// <para>选中某个物品槽</para>
@ -144,6 +188,35 @@ public partial class HotBar : HBoxContainer
{
_itemSlotNodes[oldSelectIndex].IsSelect = false;
_itemSlotNodes[newSelectIndex].IsSelect = true;
var oldItem = _itemSlotNodes[oldSelectIndex].GetItem();
if (oldItem != null && oldItem is Node2D oldNode2D)
{
oldNode2D.ProcessMode = ProcessModeEnum.Disabled;
oldNode2D.Hide();
}
var item = _itemSlotNodes[newSelectIndex].GetItem();
if (item == null)
{
LogCat.Log("选择" + oldSelectIndex + "新的为" + newSelectIndex + "空对象");
GameSceneNodeHolder.Player.CurrentItem = null;
LogCat.Log("我是空吗" + (GameSceneNodeHolder.Player.CurrentItem == null));
}
else
{
if (item is Node2D node2D)
{
LogCat.Log("我是空吗" + (GameSceneNodeHolder.Player.CurrentItem == null));
LogCat.Log("选择" + oldSelectIndex + "新的为" + newSelectIndex + "已赋值" + node2D);
node2D.ProcessMode = ProcessModeEnum.Inherit;
node2D.Show();
GameSceneNodeHolder.Player.CurrentItem = node2D;
}
else
{
GameSceneNodeHolder.Player.CurrentItem = null;
}
}
}
/// <summary>

View File

@ -30,12 +30,69 @@ public partial class ItemSlotNode : MarginContainer
{
_backgroundTextureRect.Texture = _backgroundTexture;
}
_isSelect = value;
}
}
public TextureRect BackgroundTextureRect => _backgroundTextureRect;
/// <summary>
/// <para>Get the items in the item slot</para>
/// <para>获取物品槽内的物品</para>
/// </summary>
/// <returns></returns>
public IItem? GetItem()
{
return _item;
}
/// <summary>
/// <para>Removes the specified number of items from the item slot</para>
/// <para>在物品槽内移除指定数量的物品</para>
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
public bool RemoveItem(int number)
{
if (_item == null)
{
return false;
}
var newNumber = _item.Quantity - number;
if (newNumber <= 0)
{
//If the specified number of items is removed, the number of items is less than or equal to 0. Then we return the removal successful and empty the inventory.
//如果移除指定数量的物品后物品数量小于或等于0。那么我们返回移除成功并清空物品栏。
ClearItem();
return true;
}
else
{
_item.Quantity = newNumber;
UpdateTooltipText(_item);
UpdateQuantityLabel(_item.Quantity);
return true;
}
}
/// <summary>
/// <para>Empty the items in the item slot</para>
/// <para>清空物品槽内的物品</para>
/// </summary>
/// <remarks>
///<para>This method does not calculate how many items should be left. If you want to remove a specified number of items, call the RemoveItem method.</para>
///<para>此方法不会计算物品应该剩余多少个。若您希望移除指定数量的物品请调用RemoveItem方法。</para>
/// </remarks>
public void ClearItem()
{
_item = null;
_iconTextureRect.Texture = null;
_control.TooltipText = null;
_quantityLabel.Visible = false;
}
/// <summary>
/// <para>Sets items for the item slot</para>
/// <para>为物品槽设置物品</para>

View File

@ -63,9 +63,10 @@ public partial class GameSceneLoader : SceneLoaderTemplate
{
_mapGenerator.Generate(_mapGeneratorConfig);
var packedScene = GD.Load<PackedScene>("res://prefab/entitys/Character.tscn");
//Register players in the holder
//在持有者内注册玩家
GameSceneNodeHolder.Player = (Player)packedScene.Instantiate();
var node2D = (Node2D)packedScene.Instantiate();
GameSceneNodeHolder.Player = node2D as Player;
var gameRoot = GetNode<Node2D>(".");
gameRoot.AddChild(node2D);
node2D.Position = new Vector2(55, 70);
@ -75,6 +76,7 @@ public partial class GameSceneLoader : SceneLoaderTemplate
gameRoot.AddChild(delivererOfDarkMagicPackedSceneNode2D);
delivererOfDarkMagicPackedSceneNode2D.Position = new Vector2(70, 70);
//Load a weapon
//加载武器
var w = GD.Load<PackedScene>("res://prefab/weapons/staffOfTheUndead.tscn");
for (int i = 0; i < 3; i++)

View File

@ -30,7 +30,7 @@ public partial class WeaponTemplate : RigidBody2D, IItem
/// <para>Owner</para>
/// <para>主人</para>
/// </summary>
public Node2D Owner { get; set; }
public Node2D? Owner { get; set; }
/// <summary>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 161 B

After

Width:  |  Height:  |  Size: 148 B