Compare commits

..

2 Commits

Author SHA1 Message Date
39ca716e3d
Conduct code reviews.
进行代码审查。
2024-06-05 21:38:45 +08:00
2a836e32e6
Support for restarting the game.
支持重新开始游戏了。
2024-06-04 22:23:06 +08:00
45 changed files with 733 additions and 382 deletions

5
locals/DeathInfo.csv Normal file
View File

@ -0,0 +1,5 @@
id,zh,en,jp
#kill self
#自杀
death_info_self_1,{0}误伤了自己。,{0} accidentally shot himself.,{0}誤って自分を傷つけました。
death_info_self_2,{0}忘记了瞄准。,{0} forgot to aim.,{0}照準を忘れました。
1 id,zh,en,jp
2 #kill self
3 #自杀
4 death_info_self_1,{0}误伤了自己。,{0} accidentally shot himself.,{0}誤って自分を傷つけました。
5 death_info_self_2,{0}忘记了瞄准。,{0} forgot to aim.,{0}照準を忘れました。

View File

@ -0,0 +1,17 @@
[remap]
importer="csv_translation"
type="Translation"
uid="uid://dwx0hwuy0uqio"
[deps]
files=["res://locals/DeathInfo.zh.translation", "res://locals/DeathInfo.en.translation", "res://locals/DeathInfo.jp.translation"]
source_file="res://locals/DeathInfo.csv"
dest_files=["res://locals/DeathInfo.zh.translation", "res://locals/DeathInfo.en.translation", "res://locals/DeathInfo.jp.translation"]
[params]
compress=true
delimiter=0

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -13,10 +13,10 @@ collision_layer = 0
collision_mask = 0
script = ExtResource("1_ib3qh")
metadata/Speed = 500.0
metadata/Life = 10.0
metadata/Durability = 1.0
metadata/DamageType = 2
metadata/Knockback = Vector2(2, -3)
metadata/Life = 5000
[node name="CurseOfTheUndead" type="Sprite2D" parent="."]
texture = ExtResource("1_k8el6")

View File

@ -146,7 +146,7 @@ hotbar_previous={
[internationalization]
locale/translations=PackedStringArray("res://locals/UI.en.translation", "res://locals/UI.zh.translation", "res://locals/Log.en.translation", "res://locals/Log.zh.translation", "res://locals/Weapon.en.translation", "res://locals/Weapon.zh.translation", "res://locals/InputMapping.en.translation", "res://locals/InputMapping.zh.translation", "res://locals/InputMapping.jp.translation", "res://locals/Log.jp.translation", "res://locals/UI.jp.translation", "res://locals/Weapon.jp.translation", "res://locals/Slogan.en.translation", "res://locals/Slogan.jp.translation", "res://locals/Slogan.zh.translation")
locale/translations=PackedStringArray("res://locals/UI.en.translation", "res://locals/UI.zh.translation", "res://locals/Log.en.translation", "res://locals/Log.zh.translation", "res://locals/Weapon.en.translation", "res://locals/Weapon.zh.translation", "res://locals/InputMapping.en.translation", "res://locals/InputMapping.zh.translation", "res://locals/InputMapping.jp.translation", "res://locals/Log.jp.translation", "res://locals/UI.jp.translation", "res://locals/Weapon.jp.translation", "res://locals/Slogan.en.translation", "res://locals/Slogan.jp.translation", "res://locals/Slogan.zh.translation", "res://locals/DeathInfo.en.translation", "res://locals/DeathInfo.jp.translation", "res://locals/DeathInfo.zh.translation")
[layer_names]

View File

@ -55,6 +55,6 @@ layout_mode = 2
theme_override_constants/margin_top = 10
theme_override_constants/margin_bottom = 150
[node name="Button" type="Button" parent="CenterContainer/VBoxContainer/MarginContainer2"]
[node name="RestartButton" type="Button" parent="CenterContainer/VBoxContainer/MarginContainer2"]
layout_mode = 2
text = "restart"

View File

@ -8,7 +8,11 @@ namespace ColdMint.scripts;
public static class Config
{
public class BehaviorTreeId
/// <summary>
/// <para>ID of the behavior tree</para>
/// <para>行为树的ID</para>
/// </summary>
public static class BehaviorTreeId
{
/// <summary>
/// <para>巡逻</para>
@ -21,7 +25,7 @@ public static class Config
/// <para>BehaviorTreeResult</para>
/// <para>行为树的结果</para>
/// </summary>
public class BehaviorTreeResult
public static class BehaviorTreeResult
{
/// <summary>
/// <para>Running</para>
@ -149,13 +153,18 @@ public static class Config
return OS.HasFeature("editor");
}
public class RoomInjectionProcessorId
/// <summary>
/// <para>Room Injector ID</para>
/// <para>房间注入器ID</para>
/// </summary>
public static class RoomInjectionProcessorId
{
/// <summary>
/// <para>Chance</para>
/// <para>概率的</para>
/// </summary>
public const string Chance = "Chance";
/// <summary>
/// <para>TimeInterval</para>
/// <para>时间范围的</para>
@ -191,11 +200,7 @@ public static class Config
//The host operating system is a web browser
//宿主操作系统是网页浏览器
Web,
//Editor
//编辑器
// Editor
Web
}
/// <summary>
@ -205,11 +210,6 @@ public static class Config
/// <returns></returns>
public static OsEnum GetOs()
{
// if (OS.HasFeature("editor"))
// {
// return OsEnum.Editor;
// }
if (OS.HasFeature("windows"))
{
return OsEnum.Windows;
@ -239,9 +239,15 @@ public static class Config
{
return OsEnum.Ios;
}
return OsEnum.Unknown;
}
/// <summary>
/// <para>Get the game version</para>
/// <para>获取游戏版本</para>
/// </summary>
/// <returns></returns>
public static string GetVersion()
{
var stringBuilder = new StringBuilder();
@ -347,7 +353,7 @@ public static class Config
/// <para>Physical collision layer number</para>
/// <para>物理碰撞层 序号</para>
/// </summary>
public class LayerNumber
public static class LayerNumber
{
public const int RoomArea = 1;
public const int Ground = 2;
@ -358,23 +364,7 @@ public static class Config
public const int Mob = 7;
}
/// <summary>
/// <para>The event of entering the room</para>
/// <para>进入房间的事件</para>
/// </summary>
public class EnterRoomEventId
{
}
/// <summary>
/// <para>Exit the room event</para>
/// <para>退出房间的事件</para>
/// </summary>
public class ExitRoomEventId
{
}
public class RoomDataTag
public static class RoomDataTag
{
/// <summary>
/// <para>Mark the starting room</para>
@ -387,7 +377,7 @@ public static class Config
/// <para>Specify the type of damage used in the game</para>
/// <para>指定游戏内使用的伤害类型</para>
/// </summary>
public class DamageType
public static class DamageType
{
/// <summary>
/// <para>physical injury</para>

View File

@ -3,7 +3,11 @@ using ColdMint.scripts.map.events;
namespace ColdMint.scripts;
public class EventManager
/// <summary>
/// <para>EventManager</para>
/// <para>事件管理器</para>
/// </summary>
public static class EventManager
{
/// <summary>
/// <para>Event when the AI character is generated</para>
@ -11,8 +15,18 @@ public class EventManager
/// </summary>
public static Action<AiCharacterGenerateEvent>? AiCharacterGenerateEvent;
/// <summary>
/// <para>Game Over Event</para>
/// <para>游戏结束事件</para>
/// </summary>
public static Action<GameOverEvent>? GameOverEvent;
/// <summary>
/// <para>Events when the game is replayed</para>
/// <para>游戏重玩时的事件</para>
/// </summary>
public static Action<GameReplayEvent>? GameReplayEvent;
/// <summary>
/// <para>Map starts generating events</para>
/// <para>地图开始生成的事件</para>

View File

@ -8,12 +8,14 @@ namespace ColdMint.scripts;
/// </summary>
public partial class FpsLabel : Label
{
bool _enable;
private bool _enable;
private LabelSettings? _labelSettings;
public override void _Ready()
{
Text = null;
//Enabled only in debug mode.
//仅在调试模式启用。
if (Config.IsDebug())
{
_labelSettings = new LabelSettings();

View File

@ -22,17 +22,34 @@ public static class GameSceneNodeHolder
/// </summary>
public static Node2D? WeaponContainer { get; set; }
/// <summary>
/// <para>PlayerContainer</para>
/// <para>玩家容器</para>
/// </summary>
public static Node2D? PlayerContainer { get; set; }
/// <summary>
/// <para>AICharacterContainer</para>
/// <para>AICharacter角色</para>
/// </summary>
public static Node2D? AICharacterContainer { get; set; }
public static Node2D? AiCharacterContainer { get; set; }
/// <summary>
/// <para>HotBar</para>
/// <para>快捷栏</para>
/// </summary>
public static HotBar? HotBar { get; set; }
/// <summary>
/// <para>Health Bar UI</para>
/// <para>健康条UI</para>
/// </summary>
public static HealthBarUi? HealthBarUi { get; set; }
/// <summary>
/// <para>operation tip</para>
/// <para>操作提示</para>
/// </summary>
public static RichTextLabel? OperationTipLabel { get; set; }
}

View File

@ -3,10 +3,19 @@ using Godot;
namespace ColdMint.scripts;
/// <summary>
/// <para>HealthBarUi</para>
/// <para>健康条UI</para>
/// </summary>
public partial class HealthBarUi : HBoxContainer
{
private int _maxHp;
private int _currentHp;
private Texture2D? _heartFull;
private Texture2D? _heartEmpty;
private Texture2D? _heartHalf;
private Texture2D? _heartQuarter;
private Texture2D? _heartThreeFourths;
public int CurrentHp
{
@ -139,11 +148,6 @@ public partial class HealthBarUi : HBoxContainer
}
}
private Texture2D? _heartFull;
private Texture2D? _heartEmpty;
private Texture2D? _heartHalf;
private Texture2D? _heartQuarter;
private Texture2D? _heartThreeFourths;
public override void _Ready()
{

View File

@ -1,5 +1,4 @@
using System.Collections.Generic;
using ColdMint.scripts.utils;
using ColdMint.scripts.utils;
using Godot;
namespace ColdMint.scripts;

View File

@ -45,8 +45,7 @@ public class AiPickNode : BehaviorTreeNodeTemplate
{
//If it's a weapon
//如果是武器
var distance = weaponTemplate.GlobalPosition - Character.GlobalPosition;
var distanceLength = distance.Length();
var distanceLength = weaponTemplate.GlobalPosition.DistanceTo(Character.GlobalPosition);
if (distanceLength < closestDistance)
{
closestDistance = distanceLength;

View File

@ -8,7 +8,7 @@ namespace ColdMint.scripts.camp;
/// </summary>
public class Camp
{
private string _id;
private readonly string _id;
private readonly List<string> _friendlyCampIdList;
public Camp(string id)

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ColdMint.scripts.camp;
using ColdMint.scripts.damage;
using ColdMint.scripts.debug;
@ -100,7 +101,7 @@ public partial class CharacterTemplate : CharacterBody2D
//角色创建后的初始血量
private int _initialHp;
protected int MaxHp;
public int MaxHp;
/// <summary>
/// <para>The camp ID of the role</para>
@ -121,6 +122,36 @@ public partial class CharacterTemplate : CharacterBody2D
public Node[] PickingRangeBodies => PickingRangeBodiesList?.ToArray() ?? Array.Empty<Node>();
/// <summary>
/// <para>Resurrected character</para>
/// <para>复活角色</para>
/// </summary>
/// <remarks>
///<para>Sets the amount of Hp a character has after resurrection</para>
///<para>设置角色复活后拥有的Hp</para>
/// </remarks>
public void Revive(int newHp)
{
//If the new Hp is less than or equal to 0, there is no need to resurrect
//如果新的Hp小于等于0那么不需要复活
if (newHp <= 0)
{
return;
}
if (CurrentHp > 0)
{
//If the current Hp is greater than 0, there is no need to revive
//如果当前Hp大于0那么不需要复活
return;
}
//Check whether the new Hp is greater than the maximum Hp. If yes, set the current Hp to the maximum Hp. If no, set the current Hp to the new HP
//判断新的Hp是否大于最大Hp若大于那么将当前Hp设置为最大Hp否则设置为新的Hp
CurrentHp = newHp > MaxHp ? MaxHp : newHp;
Visible = true;
}
/// <summary>
/// <para>Find the nearest item within the pick up area(Does not include items currently held)</para>
/// <para>在拾捡范围内查找距离最近的物品(不包括当前持有的物品)</para>
@ -323,10 +354,10 @@ public partial class CharacterTemplate : CharacterBody2D
//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)
if (_healthBar is { Visible: true })
{
if (_healthBar != null)
var timeSpan = DateTime.Now - _lastDamageTime;
if (timeSpan > Config.HealthBarDisplaysTime)
{
_healthBar.Visible = false;
}
@ -433,7 +464,7 @@ public partial class CharacterTemplate : CharacterBody2D
/// <para>处理角色死亡的事件</para>
/// </summary>
/// <param name="damageTemplate"></param>
protected virtual void OnDie(DamageTemplate damageTemplate)
protected virtual Task OnDie(DamageTemplate damageTemplate)
{
//If the attacker is not empty and the role name is not empty, then the role death message is printed
//如果攻击者不为空,且角色名不为空,那么打印角色死亡信息
@ -451,6 +482,7 @@ public partial class CharacterTemplate : CharacterBody2D
}
QueueFree();
return Task.CompletedTask;
}
/// <summary>

View File

@ -1,6 +1,8 @@
using System;
using System.Text;
using System.Threading.Tasks;
using ColdMint.scripts.damage;
using ColdMint.scripts.deathInfo;
using ColdMint.scripts.map.events;
using ColdMint.scripts.utils;
using ColdMint.scripts.weapon;
@ -153,6 +155,11 @@ public partial class Player : CharacterTemplate
protected override void HookPhysicsProcess(ref Vector2 velocity, double delta)
{
if (!Visible)
{
return;
}
//When the collision state between the platform detection ray and the platform changes
//在平台检测射线与平台碰撞状态改变时
if (_platformDetectionRayCast2D != null && _platformDetectionRayCast2D.IsColliding() != _collidingWithPlatform)
@ -315,6 +322,11 @@ public partial class Player : CharacterTemplate
public override void _Process(double delta)
{
if (!Visible)
{
return;
}
AimTheCurrentItemAtAPoint(GetGlobalMousePosition());
var itemMarker2DPosition = Vector2.Zero;
if (ItemMarker2D != null)
@ -366,18 +378,21 @@ public partial class Player : CharacterTemplate
}
}
protected override void OnDie(DamageTemplate damageTemplate)
protected override async Task OnDie(DamageTemplate damageTemplate)
{
if (EventManager.GameOverEvent != null)
Visible = false;
if (EventManager.GameOverEvent == null)
{
var gameOverEvent = new GameOverEvent
{
DeathInfo = "\"白纸\"失手将自己杀死。"
};
EventManager.GameOverEvent(gameOverEvent);
return;
}
Visible = false;
var gameOverEvent = new GameOverEvent();
if (damageTemplate.Attacker != null)
{
gameOverEvent.DeathInfo = await DeathInfoGenerator.GenerateDeathInfo(this, damageTemplate.Attacker);
}
EventManager.GameOverEvent.Invoke(gameOverEvent);
}
protected override void EnterThePickingRangeBody(Node node)

View File

@ -12,22 +12,16 @@ public partial class DamageNumberNodeSpawn : Marker2D
private Node2D? _rootNode;
/// <summary>
/// <para>The horizontal velocity is in the X positive direction</para>
/// <para>水平速度的X正方向</para>
/// <para>The vector in the negative direction</para>
/// <para>负方向的向量</para>
/// </summary>
private int _horizontalVelocityPositiveDirection;
private Vector2 _negativeVector;
/// <summary>
/// <para>Horizontal velocity in the negative X direction</para>
/// <para>水平速度的X负方向</para>
/// <para>Vector in the positive direction</para>
/// <para>正方向的向量</para>
/// </summary>
private int _horizontalVelocityNegativeDirection;
/// <summary>
/// <para>vertical height</para>
/// <para>垂直高度</para>
/// </summary>
private int _verticalHeight;
private Vector2 _positiveVector;
/// <summary>
/// <para>物理渐变色</para>
@ -53,18 +47,31 @@ public partial class DamageNumberNodeSpawn : Marker2D
base._Ready();
_damageNumberPackedScene = GD.Load("res://prefab/ui/DamageNumber.tscn") as PackedScene;
_rootNode = GetNode<Node2D>("/root/Game/DamageNumberContainer");
_horizontalVelocityPositiveDirection = Config.CellSize * Config.HorizontalSpeedOfDamageNumbers;
_horizontalVelocityNegativeDirection = -_horizontalVelocityPositiveDirection;
_verticalHeight = -Config.CellSize * Config.VerticalVelocityOfDamageNumbers;
//The horizontal velocity is in the X positive direction
//水平速度的X正方向
var horizontalVelocityPositiveDirection = Config.CellSize * Config.HorizontalSpeedOfDamageNumbers;
//Horizontal velocity in the negative X direction
//水平速度的X负方向
var horizontalVelocityNegativeDirection = -horizontalVelocityPositiveDirection;
//vertical height
//垂直高度
var verticalHeight = -Config.CellSize * Config.VerticalVelocityOfDamageNumbers;
//Compute left and right vectors
//计算左右向量
_negativeVector = new Vector2(horizontalVelocityNegativeDirection, verticalHeight);
_positiveVector = new Vector2(horizontalVelocityPositiveDirection, verticalHeight);
_physicalGradient = new Gradient();
//Physical color from OpenColor2 to OpenColor6 (red)
//物理色 从OpenColor2 到 OpenColor6红色
_physicalGradient.SetColor(0, new Color("#ffc9c9"));
_physicalGradient.SetColor(1, new Color("#fa5252"));
_magicGradient = new Gradient();
//Magic Color from OpenColor2 to OpenColor6(Purple)
//魔法色 从OpenColor2 到 OpenColor6(紫色)
_magicGradient.SetColor(0, new Color("#d0bfff"));
_magicGradient.SetColor(1, new Color("#7950f2"));
_defaultGradient = new Gradient();
//default behavior
//默认行为
_defaultGradient.SetColor(0, new Color("#ff8787"));
_defaultGradient.SetColor(1, new Color("#fa5252"));
@ -87,7 +94,7 @@ public partial class DamageNumberNodeSpawn : Marker2D
/// <param name="damageTemplate"></param>
public void Display(DamageTemplate damageTemplate)
{
if (_damageNumberPackedScene == null)
if (_rootNode == null || _damageNumberPackedScene == null)
{
return;
}
@ -98,18 +105,22 @@ public partial class DamageNumberNodeSpawn : Marker2D
}
CallDeferred("AddDamageNumberNode", damageNumber);
damageNumber.Position = GlobalPosition;
if (damageTemplate.MoveLeft)
{
damageNumber.SetVelocity(new Vector2(_horizontalVelocityNegativeDirection, _verticalHeight));
damageNumber.SetVelocity(_negativeVector);
}
else
{
damageNumber.SetVelocity(new Vector2(_horizontalVelocityPositiveDirection, _verticalHeight));
damageNumber.SetVelocity(_positiveVector);
}
var damageLabel = damageNumber.GetNode<Label>("Label");
if (damageLabel == null)
{
return;
}
damageLabel.Text = damageTemplate.Damage.ToString();
var labelSettings = new LabelSettings();
var offset = damageTemplate.Damage / (float)damageTemplate.MaxDamage;

View File

@ -0,0 +1,81 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using ColdMint.scripts.character;
using ColdMint.scripts.utils;
using Godot;
namespace ColdMint.scripts.deathInfo;
public static class DeathInfoGenerator
{
private static List<IDeathInfoHandler>? _deathInfoHandlers;
/// <summary>
/// <para>Register the death message handler</para>
/// <para>注册死亡信息处理器</para>
/// </summary>
/// <param name="deathInfoHandler"></param>
public static void RegisterDeathInfoHandler(IDeathInfoHandler deathInfoHandler)
{
_deathInfoHandlers ??= new List<IDeathInfoHandler>();
_deathInfoHandlers.Add(deathInfoHandler);
}
/// <summary>
/// <para>Unregister the death message handler</para>
/// <para>取消注册死亡信息处理器</para>
/// </summary>
/// <param name="deathInfoHandler"></param>
public static void UnregisterDeathInfoHandler(IDeathInfoHandler deathInfoHandler)
{
if (_deathInfoHandlers == null)
{
return;
}
_deathInfoHandlers.Remove(deathInfoHandler);
}
/// <summary>
/// <para>Generate death info</para>
/// <para>生成死亡信息</para>
/// </summary>
/// <param name="victim"></param>
/// <param name="killer"></param>
/// <returns></returns>
public static async Task<string> GenerateDeathInfo(Player victim, Node killer)
{
var victimName = victim.ReadOnlyCharacterName ?? victim.Name;
string killerName = killer.Name;
if (killer is CharacterTemplate characterTemplate)
{
killerName = characterTemplate.ReadOnlyCharacterName ?? killer.Name;
}
if (_deathInfoHandlers == null || _deathInfoHandlers.Count == 0)
{
return GenerateDefaultDeathInfo(victimName, killerName) ?? string.Empty;
}
foreach (var deathInfoHandler in _deathInfoHandlers)
{
var deathInfo = await deathInfoHandler.GenerateDeathInfo(victimName, killerName, victim, killer);
if (!string.IsNullOrEmpty(deathInfo))
{
return deathInfo;
}
}
return GenerateDefaultDeathInfo(victimName, killerName) ?? string.Empty;
}
/// <summary>
/// <para>Generate a default death message</para>
/// <para>生成默认的死亡信息</para>
/// </summary>
/// <param name="victimName"></param>
/// <param name="killerName"></param>
/// <returns></returns>
private static string? GenerateDefaultDeathInfo(string victimName, string killerName)
{
return TranslationServerUtils.TranslateWithFormat("death_info", victimName, killerName);
}
}

View File

@ -0,0 +1,35 @@
using System.Threading.Tasks;
using ColdMint.scripts.character;
using Godot;
namespace ColdMint.scripts.deathInfo;
/// <summary>
/// <para>Death information processor</para>
/// <para>死亡信息处理器</para>
/// </summary>
public interface IDeathInfoHandler
{
/// <summary>
/// <para>Generate death info</para>
/// <para>生成死亡信息</para>
/// </summary>
/// <param name="victimName">
///<para>victimName</para>
///<para>受害者名称</para>
/// </param>
/// <param name="killerName">
///<para>KillerName</para>
///<para>杀手名称</para>
/// </param>
/// <param name="victim">
/// <para>victim</para>
/// <para>受害者</para>
/// </param>
/// <param name="killer">
/// <para>Killer</para>
/// <para>杀手</para>
/// </param>
/// <returns></returns>
public Task<string?> GenerateDeathInfo(string victimName, string killerName, Player victim, Node killer);
}

View File

@ -0,0 +1,25 @@
using System.Threading.Tasks;
using ColdMint.scripts.character;
using ColdMint.scripts.utils;
using Godot;
namespace ColdMint.scripts.deathInfo;
/// <summary>
/// <para>Deal with the message that your game failed due to accidental injury</para>
/// <para>处理自己误伤导致游戏失败的信息</para>
/// </summary>
public class SelfDeathInfoHandler : IDeathInfoHandler
{
private const string Prefix = "death_info_self_";
private const int Length = 2;
public Task<string?> GenerateDeathInfo(string victimName, string killerName, Player victim, Node killer)
{
if (victim != killer) return Task.FromResult<string?>(null);
var index = GD.Randi() % Length + 1;
return Task.FromResult(
TranslationServerUtils.TranslateWithFormat(Prefix + index, victimName, killerName));
}
}

View File

@ -34,7 +34,7 @@ public partial class GameSceneLoader : SceneLoaderTemplate
//Load AICharacter container
//加载AICharacter容器
var aiCharacterContainer = GetNode<Node2D>("AICharacterContainer");
GameSceneNodeHolder.AICharacterContainer = aiCharacterContainer;
GameSceneNodeHolder.AiCharacterContainer = aiCharacterContainer;
//Load player container
//加载玩家容器
var playerContainer = GetNode<Node2D>("PlayerContainer");

View File

@ -11,6 +11,7 @@ namespace ColdMint.scripts.loader.uiLoader;
public partial class GameOverLoaderMenuLoader : UiLoaderTemplate
{
private Label? _deathInfoLabel;
private Button? _restartButton;
public override void InitializeUi()
{
@ -19,11 +20,25 @@ public partial class GameOverLoaderMenuLoader : UiLoaderTemplate
public override void InitializeData()
{
_restartButton = GetNodeOrNull<Button>("CenterContainer/VBoxContainer/MarginContainer2/RestartButton");
_deathInfoLabel =
GetNode<Label>("CenterContainer/VBoxContainer/MarginContainer/CenterContainer2/DeathInfoLabel");
EventManager.GameOverEvent += OnGameOver;
}
public override void LoadUiActions()
{
if (_restartButton != null)
{
_restartButton.Pressed += () =>
{
var replayEvent = new GameReplayEvent();
EventManager.GameReplayEvent?.Invoke(replayEvent);
Visible = false;
};
}
}
private void OnGameOver(GameOverEvent gameOverEvent)
{
if (_deathInfoLabel == null)

View File

@ -2,6 +2,7 @@ using System;
using System.IO;
using System.Text;
using ColdMint.scripts.camp;
using ColdMint.scripts.deathInfo;
using ColdMint.scripts.debug;
using ColdMint.scripts.map;
using ColdMint.scripts.map.roomInjectionProcessor;
@ -38,6 +39,7 @@ public partial class MainMenuLoader : UiLoaderTemplate
LogCat.MinLogLevel = LogCat.DisableAllLogLevel;
}
DeathInfoGenerator.RegisterDeathInfoHandler(new SelfDeathInfoHandler());
MapGenerator.RegisterRoomInjectionProcessor(new ChanceRoomInjectionProcessor());
MapGenerator.RegisterRoomInjectionProcessor(new TimeIntervalRoomInjectorProcessor());
//Register the corresponding encoding provider to solve the problem of garbled Chinese path of the compressed package

View File

@ -38,12 +38,12 @@ public partial class AiCharacterSpawn : Marker2D
return;
}
if (GameSceneNodeHolder.AICharacterContainer == null)
if (GameSceneNodeHolder.AiCharacterContainer == null)
{
return;
}
GameSceneNodeHolder.AICharacterContainer.AddChild(aiCharacter);
GameSceneNodeHolder.AiCharacterContainer.AddChild(aiCharacter);
aiCharacter.Position = GlobalPosition;
}

View File

@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Threading.Tasks;
using ColdMint.scripts.debug;
using ColdMint.scripts.levelGraphEditor;
@ -149,9 +148,9 @@ public static class MapGenerator
return;
}
if (GameSceneNodeHolder.AICharacterContainer != null)
if (GameSceneNodeHolder.AiCharacterContainer != null)
{
NodeUtils.DeleteAllChild(GameSceneNodeHolder.AICharacterContainer);
NodeUtils.DeleteAllChild(GameSceneNodeHolder.AiCharacterContainer);
}
NodeUtils.DeleteAllChild(_mapRoot);

View File

@ -18,21 +18,26 @@ public partial class PlayerSpawn : Marker2D
base._Ready();
_playerPackedScene = GD.Load<PackedScene>("res://prefab/entitys/Character.tscn");
EventManager.MapGenerationCompleteEvent += MapGenerationCompleteEvent;
EventManager.GameReplayEvent += GameReplayEvent;
}
private void MapGenerationCompleteEvent(MapGenerationCompleteEvent mapGenerationCompleteEvent)
private void GameReplayEvent(GameReplayEvent gameReplayEvent)
{
EventManager.MapGenerationCompleteEvent -= MapGenerationCompleteEvent;
//After the map is generated, create the player instance.
//当地图生成完成后,创建玩家实例。
if (GameSceneNodeHolder.Player != null)
{
//An existing player instance will not be created.
//已经存在玩家实例,不再创建。
GameSceneNodeHolder.Player.Position = GlobalPosition;
GameSceneNodeHolder.Player.Revive(GameSceneNodeHolder.Player.MaxHp);
return;
}
SpawnPlayer();
}
/// <summary>
/// <para>Generate player instance</para>
/// <para>生成玩家实例</para>
/// </summary>
private void SpawnPlayer()
{
if (GameSceneNodeHolder.PlayerContainer == null)
{
return;
@ -57,9 +62,24 @@ public partial class PlayerSpawn : Marker2D
LogCat.LogWithFormat("player_spawn_debug", player.ReadOnlyCharacterName, player.Position);
}
private void MapGenerationCompleteEvent(MapGenerationCompleteEvent mapGenerationCompleteEvent)
{
//After the map is generated, create the player instance.
//当地图生成完成后,创建玩家实例。
if (GameSceneNodeHolder.Player != null)
{
//An existing player instance will not be created.
//已经存在玩家实例,不再创建。
return;
}
SpawnPlayer();
}
public override void _ExitTree()
{
base._ExitTree();
EventManager.MapGenerationCompleteEvent -= MapGenerationCompleteEvent;
EventManager.GameReplayEvent -= GameReplayEvent;
}
}

View File

@ -1,15 +0,0 @@
using Godot;
namespace ColdMint.scripts.map;
public partial class RoomAreaDetector : Node2D
{
private Area2D? _area2D;
public override void _Ready()
{
base._Ready();
_area2D = GetNode<Area2D>("Area2D");
}
}

View File

@ -0,0 +1,10 @@
namespace ColdMint.scripts.map.events;
/// <summary>
/// <para>Game replay event</para>
/// <para>游戏重玩事件</para>
/// </summary>
public class GameReplayEvent
{
}

View File

@ -12,211 +12,220 @@ namespace ColdMint.scripts.projectile;
/// </summary>
public partial class ProjectileTemplate : CharacterBody2D
{
protected Timer? Timer;
protected long Life;
protected double Life;
//The durability of the projectile
//抛射体的耐久度
//When the projectile hits the object, the durability will be reduced, and when the durability is less than or equal to 0, the projectile will be destroyed
//当抛射体撞击到物体时会减少耐久度当耐久度小于等于0时销毁抛射体
protected double Durability;
//The durability of the projectile
//抛射体的耐久度
//When the projectile hits the object, the durability will be reduced, and when the durability is less than or equal to 0, the projectile will be destroyed
//当抛射体撞击到物体时会减少耐久度当耐久度小于等于0时销毁抛射体
protected double Durability;
protected int MaxDamage;
protected int MinDamage;
protected int DamageType;
protected int MaxDamage;
protected int MinDamage;
protected int DamageType;
//We use the Time node to specify when to destroy the projectile
//我们用Time节点来指定何时销毁抛射体
private Timer? _timer;
/// <summary>
/// <para>The impact area of the bullet</para>
/// <para>子弹的碰撞区域</para>
/// </summary>
protected Area2D? Area2D;
/// <summary>
/// <para>knockback</para>
/// <para>击退</para>
/// </summary>
/// <remarks>
///<para>How much force does it have when hitting the character? Unit: Number of cellsThe X direction of the force is inferred automatically.</para>
///<para>当击中角色时带有多大的力单位格数力的X方向是自动推断的。</para>
/// </remarks>
protected Vector2 KnockbackForce;
public float Speed
{
get => GetMeta("Speed", "15").AsSingle();
}
/// <summary>
/// <para>The master of the weapon</para>
/// <para>武器的主人</para>
/// </summary>
public new Node2D? Owner { get; set; }
public override void _Ready()
{
//子弹的碰撞检测区域
Area2D = GetNode<Area2D>("CollisionDetectionArea");
Area2D.Monitoring = true;
Area2D.BodyEntered += OnBodyEnter;
Area2D.BodyExited += OnBodyExited;
Durability = GetMeta("Durability", "1").AsDouble();
MaxDamage = GetMeta("MaxDamage", "7").AsInt32();
MinDamage = GetMeta("MinDamage", "5").AsInt32();
DamageType = GetMeta("DamageType", Config.DamageType.Physical).AsInt32();
KnockbackForce = GetMeta("Knockback", Vector2.Zero).AsVector2();
//子弹的存在时间
Life = GetMeta("Life", "10").AsDouble();
//如果存在时间小于等于0那么设置为存在10秒禁止无限期存在的抛射体
if (Life <= 0)
{
Life = 10;
}
Timer = new Timer();
AddChild(Timer);
Timer.WaitTime = Life;
Timer.OneShot = true;
Timer.Start();
Timer.Timeout += OnTimeOut;
}
/// <summary>
/// <para>After this time destroy the projectile</para>
/// <para>超过此时刻销毁抛射体</para>
/// </summary>
private DateTime? _destructionTime;
/// <summary>
/// <para>Detect whether harm is allowed</para>
/// <para>检测是否允许造成伤害</para>
/// </summary>
/// <param name="owner"></param>
/// <param name="target"></param>
/// <returns></returns>
private bool CanCauseHarm(Node2D? owner, Node2D target)
{
//We must know who the owner of the bullet is in order to determine whether it should cause damage or not
//我们必须知道子弹的主人是谁,才能判断是否应该造成伤害
if (owner == null)
{
return false;
}
/// <summary>
/// <para>The impact area of the bullet</para>
/// <para>子弹的碰撞区域</para>
/// </summary>
protected Area2D? Area2D;
if (owner is not CharacterTemplate ownerCharacterTemplate)
{
return false;
}
/// <summary>
/// <para>knockback</para>
/// <para>击退</para>
/// </summary>
/// <remarks>
///<para>How much force does it have when hitting the character? Unit: Number of cellsThe X direction of the force is inferred automatically.</para>
///<para>当击中角色时带有多大的力单位格数力的X方向是自动推断的。</para>
/// </remarks>
protected Vector2 KnockbackForce;
if (target is TileMap)
{
//When we hit the tile, we return true in order to place the bullet through the tile.
//撞击到瓦片时我们返回true是为了放置子弹穿透瓦片。
return true;
}
public float Speed => GetMeta("Speed", "15").AsSingle();
if (target is not CharacterTemplate characterTemplate)
{
return false;
}
/// <summary>
/// <para>The master of the weapon</para>
/// <para>武器的主人</para>
/// </summary>
public new Node2D? Owner { get; set; }
//First get the owner's camp and compare it with the target camp
//先获取主人的阵营与目标阵营进行比较
var canCauseHarm = CampManager.CanCauseHarm(CampManager.GetCamp(ownerCharacterTemplate.CampId),
CampManager.GetCamp(characterTemplate.CampId));
return canCauseHarm;
}
public override void _Ready()
{
//The bullet's impact detection area
//子弹的碰撞检测区域
Area2D = GetNode<Area2D>("CollisionDetectionArea");
Area2D.Monitoring = true;
Area2D.BodyEntered += OnBodyEnter;
Area2D.BodyExited += OnBodyExited;
Durability = GetMeta("Durability", "1").AsDouble();
MaxDamage = GetMeta("MaxDamage", "7").AsInt32();
MinDamage = GetMeta("MinDamage", "5").AsInt32();
DamageType = GetMeta("DamageType", Config.DamageType.Physical).AsInt32();
KnockbackForce = GetMeta("Knockback", Vector2.Zero).AsVector2();
//life(ms)
//子弹的存在时间(毫秒)
Life = GetMeta("Life", "10000").AsInt64();
//If the existence time is less than or equal to 0, then it is set to exist for 10 seconds, and projectiles that exist indefinitely are prohibited
//如果存在时间小于等于0那么设置为存在10秒禁止无限期存在的抛射体
if (Life <= 0)
{
Life = 10000;
}
/// <summary>
/// <para>Executive injury treatment</para>
/// <para>执行伤害处理</para>
/// </summary>
/// <param name="owner"></param>
/// <param name="target"></param>
private void DoDamage(Node2D? owner, Node2D target)
{
if (target is not CharacterTemplate characterTemplate)
{
return;
}
//Allow damage to be caused
//允许造成伤害
var damage = new Damage();
damage.Attacker = owner;
damage.MaxDamage = MaxDamage;
damage.MinDamage = MinDamage;
damage.CreateDamage();
damage.MoveLeft = Velocity.X < 0;
damage.Type = DamageType;
characterTemplate.Damage(damage);
if (KnockbackForce != Vector2.Zero)
{
//If we set the attack force, then apply the force to the object
//如果我们设置了攻退力,那么将力应用到对象上
var force = new Vector2();
var forceX = Math.Abs(KnockbackForce.X);
if (Velocity.X < 0)
{
//Beat back to port
//向左击退
forceX = -forceX;
}
force.X = forceX * Config.CellSize;
force.Y = KnockbackForce.Y * Config.CellSize;
characterTemplate.AddForce(force);
}
}
/// <summary>
/// <para>When the bullet is in contact with the node</para>
/// <para>当子弹与节点接触时</para>
/// </summary>
/// <param name="node"></param>
protected virtual void OnBodyEnter(Node2D node)
{
//Here we test whether harm is allowed, notice that for TileMap, we directly allow harm.
//这里我们检测是否允许造成伤害注意对于TileMap我们直接允许造成伤害。
var canCauseHarm = CanCauseHarm(Owner, node);
if (!canCauseHarm)
{
return;
}
DoDamage(Owner, node);
//Please specify in the Mask who the bullet will collide with
//请在Mask内配置子弹会和谁碰撞
//When a bullet hits an object, its durability decreases
//子弹撞击到物体时,耐久度减少
Durability--;
if (Durability <= 0)
{
//When the durability is less than or equal to 0, destroy the bullet
//当耐久度小于等于0时销毁子弹
QueueFree();
}
}
/// <summary>
/// <para>When the bullet leaves the node</para>
/// <para>当子弹离开节点时</para>
/// </summary>
/// <param name="node"></param>
protected virtual void OnBodyExited(Node2D node)
{
}
_destructionTime = DateTime.Now.AddMilliseconds(Life);
}
/// <summary>
/// <para>When beyond the time of existence</para>
/// <para>当超过存在时间</para>
/// </summary>
private void OnTimeOut()
{
QueueFree();
}
/// <summary>
/// <para>Detect whether harm is allowed</para>
/// <para>检测是否允许造成伤害</para>
/// </summary>
/// <param name="owner"></param>
/// <param name="target"></param>
/// <returns></returns>
private bool CanCauseHarm(Node2D? owner, Node2D target)
{
//We must know who the owner of the bullet is in order to determine whether it should cause damage or not
//我们必须知道子弹的主人是谁,才能判断是否应该造成伤害
if (owner == null)
{
return false;
}
public override void _PhysicsProcess(double delta)
{
MoveAndSlide();
}
if (owner is not CharacterTemplate ownerCharacterTemplate)
{
return false;
}
if (target is TileMap)
{
//When we hit the tile, we return true in order to place the bullet through the tile.
//撞击到瓦片时我们返回true是为了放置子弹穿透瓦片。
return true;
}
if (target is not CharacterTemplate characterTemplate)
{
return false;
}
//First get the owner's camp and compare it with the target camp
//先获取主人的阵营与目标阵营进行比较
var canCauseHarm = CampManager.CanCauseHarm(CampManager.GetCamp(ownerCharacterTemplate.CampId),
CampManager.GetCamp(characterTemplate.CampId));
return canCauseHarm;
}
/// <summary>
/// <para>Executive injury treatment</para>
/// <para>执行伤害处理</para>
/// </summary>
/// <param name="owner"></param>
/// <param name="target"></param>
private void DoDamage(Node2D? owner, Node2D target)
{
if (target is not CharacterTemplate characterTemplate)
{
return;
}
//Allow damage to be caused
//允许造成伤害
var damage = new Damage
{
Attacker = owner,
MaxDamage = MaxDamage,
MinDamage = MinDamage
};
damage.CreateDamage();
damage.MoveLeft = Velocity.X < 0;
damage.Type = DamageType;
characterTemplate.Damage(damage);
if (KnockbackForce != Vector2.Zero)
{
//If we set the attack force, then apply the force to the object
//如果我们设置了攻退力,那么将力应用到对象上
var force = new Vector2();
var forceX = Math.Abs(KnockbackForce.X);
if (Velocity.X < 0)
{
//Beat back to port
//向左击退
forceX = -forceX;
}
force.X = forceX * Config.CellSize;
force.Y = KnockbackForce.Y * Config.CellSize;
characterTemplate.AddForce(force);
}
}
/// <summary>
/// <para>When the bullet is in contact with the node</para>
/// <para>当子弹与节点接触时</para>
/// </summary>
/// <param name="node"></param>
protected virtual void OnBodyEnter(Node2D node)
{
//Here we test whether harm is allowed, notice that for TileMap, we directly allow harm.
//这里我们检测是否允许造成伤害注意对于TileMap我们直接允许造成伤害。
var canCauseHarm = CanCauseHarm(Owner, node);
if (!canCauseHarm)
{
return;
}
DoDamage(Owner, node);
//Please specify in the Mask who the bullet will collide with
//请在Mask内配置子弹会和谁碰撞
//When a bullet hits an object, its durability decreases
//子弹撞击到物体时,耐久度减少
Durability--;
if (Durability <= 0)
{
//When the durability is less than or equal to 0, destroy the bullet
//当耐久度小于等于0时销毁子弹
QueueFree();
}
}
/// <summary>
/// <para>When the bullet leaves the node</para>
/// <para>当子弹离开节点时</para>
/// </summary>
/// <param name="node"></param>
protected virtual void OnBodyExited(Node2D node)
{
}
/// <summary>
/// <para>When beyond the time of existence</para>
/// <para>当超过存在时间</para>
/// </summary>
private void OnTimeOut()
{
QueueFree();
}
public override void _Process(double delta)
{
//If the existence time is exceeded, the projectile is destroyed
//如果超过了存在时间,那么销毁抛射体
if (DateTime.Now >= _destructionTime)
{
OnTimeOut();
}
}
public override void _PhysicsProcess(double delta)
{
MoveAndSlide();
}
}

View File

@ -5,9 +5,13 @@ using System.Threading.Tasks;
namespace ColdMint.scripts.serialization;
/// <summary>
/// <para>JsonSerialization</para>
/// <para>Json序列化工具</para>
/// </summary>
public static class JsonSerialization
{
private static JsonSerializerOptions _options = new JsonSerializerOptions
private static readonly JsonSerializerOptions Options = new()
{
//Case-insensitive attribute matching
//不区分大小写的属性匹配
@ -30,7 +34,7 @@ public static class JsonSerialization
public static async Task<T?> ReadJsonFileToObj<T>(string path)
{
await using var openStream = File.OpenRead(path);
return await JsonSerializer.DeserializeAsync<T>(openStream, _options);
return await JsonSerializer.DeserializeAsync<T>(openStream, Options);
}
/// <summary>
@ -41,7 +45,7 @@ public static class JsonSerialization
/// <returns></returns>
public static string Serialize(object obj)
{
return JsonSerializer.Serialize(obj, _options);
return JsonSerializer.Serialize(obj, Options);
}
/// <summary>
@ -53,11 +57,11 @@ public static class JsonSerialization
/// <returns></returns>
public static T? Deserialize<T>(string json)
{
return JsonSerializer.Deserialize<T>(json, _options);
return JsonSerializer.Deserialize<T>(json, Options);
}
public static async Task<T?> ReadJsonFileToObj<T>(Stream openStream)
{
return await JsonSerializer.DeserializeAsync<T>(openStream, _options);
return await JsonSerializer.DeserializeAsync<T>(openStream, Options);
}
}

View File

@ -2,7 +2,11 @@
namespace ColdMint.scripts.utils;
public class CoordinateUtils
/// <summary>
/// <para>CoordinateUtils</para>
/// <para>坐标工具类</para>
/// </summary>
public static class CoordinateUtils
{
/// <summary>
/// <para>方向描述</para>

View File

@ -1,4 +1,5 @@
using System.Diagnostics;
using System;
using System.Diagnostics;
namespace ColdMint.scripts.utils;
@ -6,7 +7,7 @@ namespace ColdMint.scripts.utils;
/// <para>Explorer Utils</para>
/// <para>资源管理器工具</para>
/// </summary>
public class ExplorerUtils
public static class ExplorerUtils
{
/// <summary>
/// <para>Call Explorer to open the directory</para>
@ -53,6 +54,12 @@ public class ExplorerUtils
};
Process.Start(startInfoAndroid);
break;
case Config.OsEnum.Unknown:
case Config.OsEnum.Macos:
case Config.OsEnum.Ios:
case Config.OsEnum.Web:
default:
throw new ArgumentOutOfRangeException();
}
}
@ -64,14 +71,10 @@ public class ExplorerUtils
public static bool SupportOpenDirectory()
{
var osEnum = Config.GetOs();
switch (osEnum)
return osEnum switch
{
case Config.OsEnum.Windows:
case Config.OsEnum.Linux:
case Config.OsEnum.Android:
return true;
default:
return false;
}
Config.OsEnum.Windows or Config.OsEnum.Linux or Config.OsEnum.Android => true,
_ => false
};
}
}

View File

@ -2,7 +2,11 @@
namespace ColdMint.scripts.utils;
public class GuidUtils
/// <summary>
/// <para>GuidUtils</para>
/// <para>Guid工具</para>
/// </summary>
public static class GuidUtils
{
/// <summary>
/// <para>Get the new GUID</para>

View File

@ -2,7 +2,11 @@
namespace ColdMint.scripts.utils;
public class HashCodeUtils
/// <summary>
/// <para>Hash code utils</para>
/// <para>哈希码工具</para>
/// </summary>
public static class HashCodeUtils
{
/// <summary>
/// <para>Gets the hash code for a string</para>
@ -15,6 +19,8 @@ public class HashCodeUtils
/// <returns></returns>
public static uint GetFixedHashCode(string str)
{
//Turn off overflow checking to improve performance
//关闭溢出检查,以提高性能
unchecked
{
return str.Aggregate(2166136261, (current, c) => (current ^ c) * 16777619);

View File

@ -15,14 +15,10 @@ public class Md5Utils
/// <returns></returns>
public static string GetFileMd5(string filePath)
{
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(filePath))
{
var hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}
using var md5 = MD5.Create();
using var stream = File.OpenRead(filePath);
var hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
/// <summary>
@ -33,10 +29,8 @@ public class Md5Utils
/// <returns></returns>
public static string GetStringMd5(string str)
{
using (var md5 = MD5.Create())
{
var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
using var md5 = MD5.Create();
var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}

View File

@ -4,7 +4,11 @@ using Godot;
namespace ColdMint.scripts.utils;
public class NodeUtils
/// <summary>
/// <para>Node Utils</para>
/// <para>节点工具</para>
/// </summary>
public static class NodeUtils
{
/// <summary>
/// <para>Delete all child nodes</para>
@ -81,11 +85,10 @@ public class NodeUtils
continue;
}
var distance = node2D.GlobalPosition - origin.GlobalPosition;
var distanceLength = distance.Length();
if (distanceLength < closestDistance)
var distance = node2D.GlobalPosition.DistanceTo(origin.GlobalPosition);
if (distance < closestDistance)
{
closestDistance = distanceLength;
closestDistance = distance;
closestNode = node2D;
}
}

View File

@ -6,7 +6,7 @@ namespace ColdMint.scripts.utils;
/// <para>ParabolicUtils</para>
/// <para>抛物线工具</para>
/// </summary>
public class ParabolicUtils
public static class ParabolicUtils
{
/// <summary>
/// <para>Calculated parabola</para>
@ -40,7 +40,7 @@ public class ParabolicUtils
// 初始化结果数组
var points = new Vector2[numSteps];
// 计算每个采样点的位置
for (int i = 0; i < numSteps; i++)
for (var i = 0; i < numSteps; i++)
{
// 计算当前时间
var t = i * steps;

View File

@ -1,6 +1,10 @@
namespace ColdMint.scripts.utils;
public class StrUtils
/// <summary>
/// <para>StrUtils</para>
/// <para>字符串工具</para>
/// </summary>
public static class StrUtils
{
/// <summary>

View File

@ -2,6 +2,10 @@
namespace ColdMint.scripts.utils;
/// <summary>
/// <para>TileMapUtils</para>
/// <para>TileMap工具</para>
/// </summary>
public static class TileMapUtils
{
/// <summary>

View File

@ -3,6 +3,10 @@ using ColdMint.scripts.debug;
namespace ColdMint.scripts.utils;
/// <summary>
/// <para>Time Utils</para>
/// <para>时间工具</para>
/// </summary>
public static class TimeUtils
{
/// <summary>

View File

@ -2,6 +2,10 @@
namespace ColdMint.scripts.utils;
/// <summary>
/// <para>Translation server utils</para>
/// <para>翻译服务器工具</para>
/// </summary>
public static class TranslationServerUtils
{
/// <summary>

View File

@ -5,9 +5,26 @@ using Godot;
namespace ColdMint.scripts.weapon;
/// <summary>
/// <para>Projectile weapons</para>
/// <para>抛射体武器</para>
/// </summary>
/// <remarks>
///<para>These weapons can fire projectiles to attack the enemy.For example: guns and scepters.Generate a bullet to attack the enemy.</para>
///<para>这类武器可发射抛射体,攻击敌人。例如:枪支和法杖。生成一个子弹攻击敌人。</para>
/// </remarks>
public partial class ProjectileWeapon : WeaponTemplate
{
/// <summary>
/// <para>The formation position of the projectile</para>
/// <para>抛射体的生成位置</para>
/// </summary>
private Marker2D? _marker2D;
/// <summary>
/// <para>List of projectiles</para>
/// <para>抛射体列表</para>
/// </summary>
private string[]? _projectiles;
private Dictionary<string, PackedScene>? _projectileCache;
private Node2D? _projectileContainer;
@ -21,6 +38,10 @@ public partial class ProjectileWeapon : WeaponTemplate
foreach (var projectileItem in _projectiles)
{
var packedScene = GD.Load<PackedScene>(projectileItem);
if (packedScene == null)
{
continue;
}
_projectileCache.Add(projectileItem, packedScene);
}
@ -30,26 +51,25 @@ public partial class ProjectileWeapon : WeaponTemplate
protected override void DoFire(Node2D? owner, Vector2 enemyGlobalPosition)
{
if (_projectiles.IsEmpty())
{
LogCat.LogError("projectiles_is_empty");
return;
}
if (_projectileCache == null || _projectiles == null || owner == null || _projectileContainer == null ||
_marker2D == null)
{
return;
}
if (_projectiles.IsEmpty())
{
LogCat.LogError("projectiles_is_empty");
return;
}
//Get the first projectile
//获取第一个抛射体
var projectileScene = _projectileCache[_projectiles[0]];
var projectile = projectileScene.Instantiate() as ProjectileTemplate;
if (projectile != null)
{
projectile.Owner = owner;
var vector2 = (enemyGlobalPosition - _marker2D.GlobalPosition).Normalized() * projectile.Speed;
projectile.Velocity = vector2;
projectile.Velocity = (enemyGlobalPosition - _marker2D.GlobalPosition).Normalized() * projectile.Speed;
projectile.Position = _marker2D.GlobalPosition;
}

View File

@ -13,7 +13,7 @@ namespace ColdMint.scripts.weapon;
/// </summary>
public partial class WeaponTemplate : RigidBody2D, IItem
{
public float Gravity = ProjectSettings.GetSetting("physics/2d/default_gravity").AsSingle();
private float _gravity = ProjectSettings.GetSetting("physics/2d/default_gravity").AsSingle();
public string? Id { get; set; }
public int Quantity { get; set; }
@ -42,7 +42,10 @@ public partial class WeaponTemplate : RigidBody2D, IItem
private DateTime? _lastFiringTime;
//开火间隔
/// <summary>
/// <para>Firing interval</para>
/// <para>开火间隔</para>
/// </summary>
private TimeSpan _firingInterval;
@ -56,6 +59,10 @@ public partial class WeaponTemplate : RigidBody2D, IItem
/// </remarks>
private Vector2 _recoil;
/// <summary>
/// <para>This area represents the collision range of the weapon, and when other nodes enter this area, they will deal damage.</para>
/// <para>这个区域表示武器的碰撞范围,当其他节点进入此区域时,会造成伤害。</para>
/// </summary>
private Area2D? _area2D;
protected RayCast2D? RayCast2D;
@ -117,7 +124,6 @@ public partial class WeaponTemplate : RigidBody2D, IItem
//If allowed to cause harm
//如果允许造成伤害
Owner = null;
var damage = new Damage
{
MaxDamage = Math.Abs(_maxContactInjury),
@ -128,6 +134,9 @@ public partial class WeaponTemplate : RigidBody2D, IItem
damage.MoveLeft = LinearVelocity.X < 0;
damage.Type = Config.DamageType.Physical;
characterTemplate.Damage(damage);
//Can only cause one collision damage.
//仅能造成一次碰撞伤害。
EnableContactInjury = false;
}
/// <summary>
@ -177,34 +186,36 @@ public partial class WeaponTemplate : RigidBody2D, IItem
public void Fire(Node2D? owner, Vector2 enemyGlobalPosition)
{
var nowTime = DateTime.Now;
if (_lastFiringTime == null || nowTime - _lastFiringTime > _firingInterval)
//If the present time minus the time of the last fire is less than the interval between fires, it means that the fire cannot be fired yet.
//如果现在时间减去上次开火时间小于开火间隔,说明还不能开火。
if (_lastFiringTime != null && nowTime - _lastFiringTime < _firingInterval)
{
if (owner is CharacterTemplate characterTemplate)
{
//我们在每次开火之前,检查武器的后坐力。
if (_recoil != Vector2.Zero)
{
//假设此武器拥有后坐力
var force = new Vector2();
var forceX = Math.Abs(_recoil.X);
if (Math.Abs(RotationDegrees) < 90)
{
//The weapon goes to the right and we apply a recoil to the left
//武器朝向右边我们向左施加后坐力
forceX = -forceX;
}
force.X = forceX * Config.CellSize;
force.Y = _recoil.Y * Config.CellSize;
characterTemplate.AddForce(force);
}
}
//If the time difference is greater than the firing interval, then fire
//如果可以时间差大于开火间隔,那么开火
DoFire(owner, enemyGlobalPosition);
_lastFiringTime = nowTime;
return;
}
if (owner is CharacterTemplate characterTemplate)
{
//We check the recoil of the weapon before each firing.
//我们在每次开火之前,检查武器的后坐力。
if (_recoil != Vector2.Zero)
{
var force = new Vector2();
var forceX = Math.Abs(_recoil.X);
if (Math.Abs(RotationDegrees) < 90)
{
//The weapon goes to the right and we apply a recoil to the left
//武器朝向右边我们向左施加后坐力
forceX = -forceX;
}
force.X = forceX * Config.CellSize;
force.Y = _recoil.Y * Config.CellSize;
characterTemplate.AddForce(force);
}
}
DoFire(owner, enemyGlobalPosition);
_lastFiringTime = nowTime;
}
/// <summary>