-
Notifications
You must be signed in to change notification settings - Fork 10
/
CWRUtils.cs
1819 lines (1600 loc) · 74.1 KB
/
CWRUtils.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using CalamityMod;
using CalamityMod.Events;
using CalamityMod.NPCs.NormalNPCs;
using CalamityOverhaul.Common;
using CalamityOverhaul.Content;
using CalamityOverhaul.Content.Events;
using CalamityOverhaul.Content.Items;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using ReLogic.Content;
using ReLogic.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using Terraria;
using Terraria.Audio;
using Terraria.Chat;
using Terraria.DataStructures;
using Terraria.GameContent;
using Terraria.GameContent.Events;
using Terraria.Graphics.Shaders;
using Terraria.ID;
using Terraria.Localization;
using Terraria.ModLoader;
using Terraria.ObjectData;
using static CalamityMod.CalamityUtils;
namespace CalamityOverhaul
{
public static class CWRUtils
{
#region System
public static string GetTextProgressively(string text, float progress) {
// 输入保护
if (string.IsNullOrEmpty(text)) {
return string.Empty;
}
// 将进度限制在有效范围 (0.0f - 1.0f)
progress = MathHelper.Clamp(progress, 0.0f, 1.0f);
int charCountToShow = (int)(text.Length * progress);
return text.Substring(0, charCountToShow);
}
public static LocalizedText SafeGetItemName<T>() where T : ModItem {
Type type = typeof(T);
return type.BaseType == typeof(EctypeItem)
? Language.GetText($"Mods.CalamityOverhaul.Items.{(Activator.CreateInstance(type) as EctypeItem)?.Name}.DisplayName")
: GetItemName<T>();
}
public static LocalizedText SafeGetItemName(int id) {
ModItem item = ItemLoader.GetItem(id);
if (item == null) {
return CWRLocText.GetText("None");
}
return item.GetLocalization("DisplayName");
}
/// <summary>
/// 一个额外的跳字方法,向游戏内打印对象的ToString内容
/// </summary>
/// <param name="obj"></param>
public static void Domp(this object obj, Color color = default) {
if (color == default) {
color = Color.White;
}
if (obj == null) {
Text("ERROR Is Null", Color.Red);
return;
}
Text(obj.ToString(), color);
}
/// <summary>
/// 一个额外的跳字方法,向控制台面板打印对象的ToString内容,并自带换行
/// </summary>
/// <param name="obj"></param>
public static void DompInConsole(this object obj, bool outputLogger = true) {
if (obj == null) {
Console.WriteLine("ERROR Is Null");
return;
}
string value = obj.ToString();
Console.WriteLine(value);
if (outputLogger) {
CWRMod.Instance.Logger.Info(value);
}
}
/// <summary>
/// 将 Item 数组的信息写入指定路径的文件中
/// </summary>
/// <param name="items">要导出的 Item 数组</param>
/// <param name="path">写入文件的路径,默认为 "D:\\模组资源\\AAModPrivate\\input.cs"</param>
//public static void ExportItemTypesToFile(Item[] items, string path = "D:\\Mod_Resource\\input.cs") {
// try {
// int columnIndex = 0;
// using StreamWriter sw = new(path);
// sw.Write("string[] fullItems = new string[] {");
// foreach (Item item in items) {
// columnIndex++;
// // 根据是否有 ModItem 决定写入的内容
// string itemInfo = item.ModItem == null ? $"\"{item.type}\"" : $"\"{item.ModItem.FullName}\"";
// sw.Write(itemInfo);
// sw.Write(", ");
// // 每行最多写入9个元素,然后换行
// if (columnIndex >= 9) {
// sw.WriteLine();
// columnIndex = 0;
// }
// }
// sw.Write("};");
// } catch (UnauthorizedAccessException) {
// CWRMod.Instance.Logger.Info($"UnauthorizedAccessException: 无法访问文件路径 '{path}'. 权限不足");
// } catch (DirectoryNotFoundException) {
// CWRMod.Instance.Logger.Info($"DirectoryNotFoundException: 文件路径 '{path}' 中的目录不存在");
// } catch (PathTooLongException) {
// CWRMod.Instance.Logger.Info($"PathTooLongException: 文件路径 '{path}' 太长");
// } catch (IOException) {
// CWRMod.Instance.Logger.Info($"IOException: 无法打开文件 '{path}' 进行写入");
// } catch (Exception e) {
// CWRMod.Instance.Logger.Info($"An error occurred: {e.Message}");
// }
//}
public static int GetTileDorp(Tile tile) {
int stye = TileObjectData.GetTileStyle(tile);
if (stye == -1) {
stye = 0;
}
return TileLoader.GetItemDropFromTypeAndStyle(tile.TileType, stye);
}
public static Player InPosFindPlayer(Vector2 position, int maxRange = 3000) {
foreach (Player player in Main.player) {
if (!player.Alives()) {
continue;
}
if (maxRange == -1) {
return player;
}
int distance = (int)player.position.To(position).Length();
if (distance < maxRange) {
return player;
}
}
return null;
}
public static Player TileFindPlayer(int i, int j) {
return InPosFindPlayer(new Vector2(i, j) * 16, 9999);
}
public static Chest FindNearestChest(int x, int y) {
int distance = 99999;
Chest nearestChest = null;
for (int c = 0; c < Main.chest.Length; c++) {
Chest currentChest = Main.chest[c];
if (currentChest != null) {
int length = (int)Math.Sqrt(Math.Pow(x - currentChest.x, 2) + Math.Pow(y - currentChest.y, 2));
if (length < distance) {
nearestChest = currentChest;
distance = length;
}
}
}
return nearestChest;
}
public static void AddItem(this Chest chest, Item item) {
Item infoItem = item.Clone();
for (int i = 0; i < chest.item.Length; i++) {
if (chest.item[i] == null) {
chest.item[i] = new Item();
}
if (chest.item[i].type == ItemID.None) {
chest.item[i] = infoItem;
return;
}
if (chest.item[i].type == item.type) {
chest.item[i].stack += infoItem.stack;
return;
}
}
}
public static Color[] GetColorDate(Texture2D tex) {
Color[] colors = new Color[tex.Width * tex.Height];
tex.GetData(colors);
List<Color> nonTransparentColors = [];
foreach (Color color in colors) {
if ((color.A > 0 || color.R > 0 || color.G > 0 || color.B > 0) && color != Color.White && color != Color.Black) {
nonTransparentColors.Add(color);
}
}
return nonTransparentColors.ToArray();
}
#endregion
#region AIUtils
#region 工具部分
public const float atoR = MathHelper.Pi / 180;
public static float AtoR(this float num) => num * atoR;
public static float RtoA(this float num) => num / atoR;
public static void SetArrowRot(int proj) => Main.projectile[proj].rotation = Main.projectile[proj].velocity.ToRotation() + MathHelper.PiOver2;
public static void SetArrowRot(this Projectile proj) => proj.rotation = proj.velocity.ToRotation() + MathHelper.PiOver2;
/// <summary>
/// 关于火箭的弹药映射
/// </summary>
/// <param name="ammoItem"></param>
/// <returns></returns>
public static int RocketAmmo(Item ammoItem) {
int ammoTypes = ammoItem.shoot;
if (ammoItem.type == ItemID.RocketI) {
ammoTypes = ProjectileID.RocketI;
}
if (ammoItem.type == ItemID.RocketII) {
ammoTypes = ProjectileID.RocketII;
}
if (ammoItem.type == ItemID.RocketIII) {
ammoTypes = ProjectileID.RocketIII;
}
if (ammoItem.type == ItemID.RocketIV) {
ammoTypes = ProjectileID.RocketIV;
}
if (ammoItem.type == ItemID.ClusterRocketI) {
ammoTypes = ProjectileID.ClusterRocketI;
}
if (ammoItem.type == ItemID.ClusterRocketII) {
ammoTypes = ProjectileID.ClusterRocketII;
}
if (ammoItem.type == ItemID.DryRocket) {
ammoTypes = ProjectileID.DryRocket;
}
if (ammoItem.type == ItemID.WetRocket) {
ammoTypes = ProjectileID.WetRocket;
}
if (ammoItem.type == ItemID.HoneyRocket) {
ammoTypes = ProjectileID.HoneyRocket;
}
if (ammoItem.type == ItemID.LavaRocket) {
ammoTypes = ProjectileID.LavaRocket;
}
if (ammoItem.type == ItemID.MiniNukeI) {
ammoTypes = ProjectileID.MiniNukeRocketI;
}
if (ammoItem.type == ItemID.MiniNukeII) {
ammoTypes = ProjectileID.MiniNukeRocketII;
}
return ammoTypes;
}
/// <summary>
/// 雪人类弹药映射
/// </summary>
/// <param name="ammoItem"></param>
/// <returns></returns>
public static int SnowmanCannonAmmo(Item ammoItem) {
int AmmoTypes = ProjectileID.RocketSnowmanI;
switch (ammoItem.type) {
case ItemID.RocketI:
AmmoTypes = ProjectileID.RocketSnowmanI;
break;
case ItemID.RocketII:
AmmoTypes = ProjectileID.RocketSnowmanII;
break;
case ItemID.RocketIII:
AmmoTypes = ProjectileID.RocketSnowmanIII;
break;
case ItemID.RocketIV:
AmmoTypes = ProjectileID.RocketSnowmanIV;
break;
case ItemID.ClusterRocketI:
AmmoTypes = ProjectileID.ClusterSnowmanRocketI;
break;
case ItemID.ClusterRocketII:
AmmoTypes = ProjectileID.ClusterSnowmanRocketII;
break;
case ItemID.DryRocket:
AmmoTypes = ProjectileID.DrySnowmanRocket;
break;
case ItemID.WetRocket:
AmmoTypes = ProjectileID.WetSnowmanRocket;
break;
case ItemID.HoneyRocket:
AmmoTypes = ProjectileID.HoneySnowmanRocket;
break;
case ItemID.LavaRocket:
AmmoTypes = ProjectileID.LavaSnowmanRocket;
break;
case ItemID.MiniNukeI:
AmmoTypes = ProjectileID.MiniNukeSnowmanRocketI;
break;
case ItemID.MiniNukeII:
AmmoTypes = ProjectileID.MiniNukeSnowmanRocketII;
break;
}
return AmmoTypes;
}
/// <summary>
/// 如果对象是一个蠕虫体节,那么按机会分母的倒数返回布尔值,如果输入5,那么会有4/5的概率返回<see langword="true"/>
/// </summary>
/// <param name="targetNPCType"></param>
/// <param name="randomCount"></param>
/// <returns></returns>
public static bool FromWormBodysRandomSet(int targetNPCType, int randomCount) {
return CWRLoad.WormBodys.Contains(targetNPCType) && !Main.rand.NextBool(randomCount);
}
/// <summary>
/// 如果对象是一个蠕虫体节,那么按机会分母的倒数返回布尔值,如果输入5,那么会有4/5的概率返回<see langword="true"/>
/// </summary>
/// <param name="targetNPCType"></param>
/// <param name="randomCount"></param>
/// <returns></returns>
public static bool FromWormBodysRandomSet(this NPC npc, int randomCount) => FromWormBodysRandomSet(npc.type, randomCount);
/// <summary>
/// 这个NPC是否属于一个蠕虫体节
/// </summary>
/// <param name="npc"></param>
/// <returns></returns>
public static bool IsWormBody(this NPC npc) => CWRLoad.WormBodys.Contains(npc.type);
/// <summary>
/// 世界实体坐标转物块坐标
/// </summary>
/// <param name="wePos"></param>
/// <returns></returns>
public static Vector2 WEPosToTilePos(Vector2 wePos) {
int tilePosX = (int)(wePos.X / 16f);
int tilePosY = (int)(wePos.Y / 16f);
Vector2 tilePos = new(tilePosX, tilePosY);
tilePos = PTransgressionTile(tilePos);
return tilePos;
}
/// <summary>
/// 物块坐标转世界实体坐标
/// </summary>
/// <param name="tilePos"></param>
/// <returns></returns>
public static Vector2 TilePosToWEPos(Vector2 tilePos) {
float wePosX = (float)(tilePos.X * 16f);
float wePosY = (float)(tilePos.Y * 16f);
return new Vector2(wePosX, wePosY);
}
/// <summary>
/// 计算一个渐进速度值
/// </summary>
/// <param name="thisCenter">本体位置</param>
/// <param name="targetCenter">目标位置</param>
/// <param name="speed">速度</param>
/// <param name="shutdownDistance">停摆范围</param>
/// <returns></returns>
public static float AsymptoticVelocity(Vector2 thisCenter, Vector2 targetCenter, float speed, float shutdownDistance) {
Vector2 toMou = targetCenter - thisCenter;
float thisSpeed = toMou.LengthSquared() > shutdownDistance * shutdownDistance ? speed : MathHelper.Min(speed, toMou.Length());
return thisSpeed;
}
/// <summary>
/// 进行圆形的碰撞检测
/// </summary>
/// <param name="centerPosition">中心点</param>
/// <param name="radius">半径</param>
/// <param name="targetHitbox">碰撞对象的箱体结构</param>
/// <returns></returns>
public static bool CircularHitboxCollision(Vector2 centerPosition, float radius, Rectangle targetHitbox) {
if (new Rectangle((int)centerPosition.X, (int)centerPosition.Y, 1, 1).Intersects(targetHitbox)) {
return true;
}
float distanceToTopLeft = Vector2.Distance(centerPosition, targetHitbox.TopLeft());
float distanceToTopRight = Vector2.Distance(centerPosition, targetHitbox.TopRight());
float distanceToBottomLeft = Vector2.Distance(centerPosition, targetHitbox.BottomLeft());
float distanceToBottomRight = Vector2.Distance(centerPosition, targetHitbox.BottomRight());
float closestDistance = distanceToTopLeft;
if (distanceToTopRight < closestDistance) {
closestDistance = distanceToTopRight;
}
if (distanceToBottomLeft < closestDistance) {
closestDistance = distanceToBottomLeft;
}
if (distanceToBottomRight < closestDistance) {
closestDistance = distanceToBottomRight;
}
return closestDistance <= radius;
}
/// <summary>
/// 根据索引返回在player域中的player实例,同时考虑合法性校验
/// </summary>
/// <returns>当获取值非法时将返回 <see cref="null"/> </returns>
public static Player GetPlayerInstance(int playerIndex) {
if (playerIndex.ValidateIndex(Main.player)) {
Player player = Main.player[playerIndex];
return player.Alives() ? player : null;
}
else {
return null;
}
}
/// <summary>
/// 根据索引返回在npc域中的npc实例,同时考虑合法性校验
/// </summary>
/// <returns>当获取值非法时将返回 <see cref="null"/> </returns>
public static NPC GetNPCInstance(int npcIndex) {
if (npcIndex.ValidateIndex(Main.npc)) {
NPC npc = Main.npc[npcIndex];
return npc.Alives() ? npc : null;
}
else {
return null;
}
}
/// <summary>
/// 根据索引返回在projectile域中的Projectile实例,同时考虑合法性校验
/// </summary>
/// <returns>当获取值非法时将返回 <see cref="null"/> </returns>
public static Projectile GetProjectileInstance(int projectileIndex) {
if (projectileIndex.ValidateIndex(Main.projectile)) {
Projectile proj = Main.projectile[projectileIndex];
return proj.Alives() ? proj : null;
}
else {
return null;
}
}
/// <summary>
/// 获取鞭类弹幕的路径点集
/// </summary>
public static List<Vector2> GetWhipControlPoints(this Projectile projectile) {
List<Vector2> list = [];
Projectile.FillWhipControlPoints(projectile, list);
return list;
}
#endregion
#region 行为部分
public static void WulfrumAmplifierAI(NPC npc, float maxrg = 495f, int maxchargeTime = 600) {
List<int> SuperchargableEnemies = [
ModContent.NPCType<WulfrumDrone>(),
ModContent.NPCType<WulfrumGyrator>(),
ModContent.NPCType<WulfrumHovercraft>(),
ModContent.NPCType<WulfrumRover>()
];
npc.ai[1] = (int)MathHelper.Lerp(npc.ai[1], maxrg, 0.1f);
if (Main.rand.NextBool(4)) {
float dustCount = MathHelper.TwoPi * npc.ai[1] / 8f;
for (int i = 0; i < dustCount; i++) {
float angle = MathHelper.TwoPi * i / dustCount;
Dust dust = Dust.NewDustPerfect(npc.Center, 229);
dust.position = npc.Center + angle.ToRotationVector2() * npc.ai[1];
dust.scale = 0.7f;
dust.noGravity = true;
dust.velocity = npc.velocity;
}
}
for (int i = 0; i < Main.maxNPCs; i++) {
NPC npcAtIndex = Main.npc[i];
if (!npcAtIndex.active)
continue;
if (!SuperchargableEnemies.Contains(npcAtIndex.type) && npcAtIndex.type != ModContent.NPCType<WulfrumRover>())
continue;
if (npcAtIndex.ai[3] > 0f)
continue;
if (npc.Distance(npcAtIndex.Center) > npc.ai[1])
continue;
npcAtIndex.ai[3] = maxchargeTime;
npcAtIndex.netUpdate = true;
if (Main.dedServ)
continue;
for (int j = 0; j < 10; j++) {
Dust.NewDust(npcAtIndex.position, npcAtIndex.width, npcAtIndex.height, DustID.Electric);
}
}
}
public static void SpawnGunDust(Projectile projectile, Vector2 pos, Vector2 velocity, int splNum = 1) {
if (Main.myPlayer != projectile.owner) return;
pos += velocity.SafeNormalize(Vector2.Zero) * projectile.width * projectile.scale * 0.71f;
for (int i = 0; i < 30 * splNum; i++) {
int dustID;
switch (Main.rand.Next(6)) {
case 0:
dustID = 262;
break;
case 1:
case 2:
dustID = 54;
break;
default:
dustID = 53;
break;
}
float num = Main.rand.NextFloat(3f, 13f) * splNum;
float angleRandom = 0.06f;
Vector2 dustVel = new Vector2(num, 0f).RotatedBy((double)velocity.ToRotation(), default);
dustVel = dustVel.RotatedBy(0f - angleRandom);
dustVel = dustVel.RotatedByRandom(2f * angleRandom);
if (Main.rand.NextBool(4)) {
dustVel = Vector2.Lerp(dustVel, -Vector2.UnitY * dustVel.Length(), Main.rand.NextFloat(0.6f, 0.85f)) * 0.9f;
}
float scale = Main.rand.NextFloat(0.5f, 1.5f);
int idx = Dust.NewDust(pos, 1, 1, dustID, dustVel.X, dustVel.Y, 0, default, scale);
Main.dust[idx].noGravity = true;
Main.dust[idx].position = pos;
}
}
/// <summary>
/// 让弹幕进行爆炸效果的操作
/// </summary>
/// <param name="projectile">要爆炸的投射物</param>
/// <param name="blastRadius">爆炸效果的半径(默认为 120 单位)</param>
/// <param name="explosionSound">爆炸声音的样式(默认为默认的爆炸声音)</param>
public static void Explode(this Projectile projectile, int blastRadius = 120, SoundStyle explosionSound = default, bool spanSound = true) {
Vector2 originalPosition = projectile.position;
int originalWidth = projectile.width;
int originalHeight = projectile.height;
if (spanSound) {
_ = SoundEngine.PlaySound(explosionSound == default ? SoundID.Item14 : explosionSound, projectile.Center);
}
projectile.position = projectile.Center;
projectile.width = projectile.height = blastRadius * 2;
projectile.position.X -= projectile.width / 2;
projectile.position.Y -= projectile.height / 2;
projectile.maxPenetrate = -1;
projectile.penetrate = -1;
projectile.usesLocalNPCImmunity = true;
projectile.localNPCHitCooldown = -1;
projectile.Damage();
projectile.position = originalPosition;
projectile.width = originalWidth;
projectile.height = originalHeight;
}
/// <summary>
/// 普通的追逐行为
/// </summary>
/// <param name="entity">需要操纵的实体</param>
/// <param name="TargetCenter">目标地点</param>
/// <param name="Speed">速度</param>
/// <param name="ShutdownDistance">停摆距离</param>
/// <returns></returns>
public static Vector2 ChasingBehavior(this Entity entity, Vector2 TargetCenter, float Speed, float ShutdownDistance = 16) {
if (entity == null) {
return Vector2.Zero;
}
Vector2 ToTarget = TargetCenter - entity.Center;
Vector2 ToTargetNormalize = ToTarget.SafeNormalize(Vector2.Zero);
Vector2 speed = ToTargetNormalize * AsymptoticVelocity(entity.Center, TargetCenter, Speed, ShutdownDistance);
entity.velocity = speed;
return speed;
}
/// <summary>
/// 更加缓和的追逐行为
/// </summary>
/// <param name="entity">需要操纵的实体</param>
/// <param name="TargetCenter">目标地点</param>
/// <param name="SpeedUpdates">速度的更新系数</param>
/// <param name="HomingStrenght">追击力度</param>
/// <returns></returns>
public static Vector2 SmoothHomingBehavior(this Entity entity, Vector2 TargetCenter, float SpeedUpdates = 1, float HomingStrenght = 0.1f) {
float targetAngle = entity.AngleTo(TargetCenter);
float f = entity.velocity.ToRotation().RotTowards(targetAngle, HomingStrenght);
Vector2 speed = f.ToRotationVector2() * entity.velocity.Length() * SpeedUpdates;
entity.velocity = speed;
return speed;
}
/// <summary>
/// 寻找距离指定位置最近的NPC
/// </summary>
/// <param name="origin">开始搜索的位置</param>
/// <param name="maxDistanceToCheck">搜索NPC的最大距离</param>
/// <param name="ignoreTiles">在检查障碍物时是否忽略瓦片</param>
/// <param name="bossPriority">是否优先选择Boss</param>
/// <param name="onHitNPCs">排除的NPC列表</param>
/// <returns>距离最近的NPC</returns>
public static NPC FindClosestNPC(this Vector2 origin, float maxDistanceToCheck, bool ignoreTiles = true, bool bossPriority = false, IEnumerable<NPC> onHitNPCs = null) {
NPC closestTarget = null;
float distance = maxDistanceToCheck;
bool bossFound = false;
foreach (var npc in Main.npc) {
// 跳过无效的NPC
if (!npc.CanBeChasedBy() || (onHitNPCs != null && onHitNPCs.Contains(npc))) {
continue;
}
// Boss优先选择逻辑
if (bossPriority && bossFound && !npc.boss && npc.type != NPCID.WallofFleshEye) {
continue;
}
// 计算NPC与起点的距离
float extraDistance = (npc.width / 2f) + (npc.height / 2f);
float actualDistance = Vector2.Distance(origin, npc.Center);
// 检查瓦片阻挡
bool canHit = ignoreTiles || Collision.CanHit(origin, 1, 1, npc.Center, 1, 1);
// 更新最近目标
if (actualDistance < distance + extraDistance && canHit) {
if (bossPriority && (npc.boss || npc.type == NPCID.WallofFleshEye)) {
bossFound = true;
}
distance = actualDistance;
closestTarget = npc;
}
}
return closestTarget;
}
public static void EntityToRot(this NPC entity, float ToRot, float rotSpeed) {
//entity.rotation = MathHelper.SmoothStep(entity.rotation, ToRot, rotSpeed);
// 将角度限制在 -π 到 π 的范围内
entity.rotation = MathHelper.WrapAngle(entity.rotation);
// 计算差异角度
float diff = MathHelper.WrapAngle(ToRot - entity.rotation);
// 选择修改幅度小的方向进行旋转
if (Math.Abs(diff) < MathHelper.Pi) {
entity.rotation += diff * rotSpeed;
}
else {
entity.rotation -= MathHelper.WrapAngle(-diff) * rotSpeed;
}
}
/// <summary>
/// 处理实体的旋转行为
/// </summary>
public static void EntityToRot(this Projectile entity, float ToRot, float rotSpeed) {
//entity.rotation = MathHelper.SmoothStep(entity.rotation, ToRot, rotSpeed);
// 将角度限制在 -π 到 π 的范围内
entity.rotation = MathHelper.WrapAngle(entity.rotation);
// 计算差异角度
float diff = MathHelper.WrapAngle(ToRot - entity.rotation);
// 选择修改幅度小的方向进行旋转
if (Math.Abs(diff) < MathHelper.Pi) {
entity.rotation += diff * rotSpeed;
}
else {
entity.rotation -= MathHelper.WrapAngle(-diff) * rotSpeed;
}
}
#endregion
#endregion
#region GameUtils
/// <summary>
/// 是否处于入侵期间
/// </summary>
public static bool Invasion => Main.invasionType > 0 || Main.pumpkinMoon
|| Main.snowMoon || DD2Event.Ongoing || AcidRainEvent.AcidRainEventIsOngoing
|| TungstenRiot.Instance.TungstenRiotIsOngoing;
public static bool ZoneHell(this Player player) => player.position.Y > Main.maxTilesY * 16f / 15f * 14f;
public static bool IsTool(this Item item) => item.pick > 0 || item.axe > 0 || item.hammer > 0;
public static void GiveMeleeType(this Item item, bool isGiveTrueMelee = false) => item.DamageType = GiveMeleeType(isGiveTrueMelee);
public static DamageClass GiveMeleeType(bool isGiveTrueMelee = false) => isGiveTrueMelee ? ModContent.GetInstance<TrueMeleeDamageClass>() : DamageClass.Melee;
/// <summary>
/// 目标弹药是否应该判定为一个木箭
/// </summary>
/// <param name="player"></param>
/// <param name="ammoType"></param>
/// <returns></returns>
public static bool IsWoodenAmmo(this Player player, int ammoType) {
if (player.hasMoltenQuiver && ammoType == ProjectileID.FireArrow) {
return true;
}
if (ammoType == ProjectileID.WoodenArrowFriendly) {
return true;
}
return false;
}
public static void SetItemLegendContentTops(ref List<TooltipLine> tooltips, string itemKey) {
TooltipLine legendtops = tooltips.FirstOrDefault((TooltipLine x) => x.Text.Contains("[legend]") && x.Mod == "Terraria");
if (legendtops != null) {
KeyboardState state = Keyboard.GetState();
if ((state.IsKeyDown(Keys.LeftShift) || state.IsKeyDown(Keys.RightShift))) {
legendtops.Text = Language.GetTextValue($"Mods.CalamityOverhaul.Items.{itemKey}.Legend");
legendtops.OverrideColor = Color.Lerp(Color.BlueViolet, Color.White, 0.5f + (float)Math.Sin(Main.GlobalTimeWrappedHourly) * 0.5f);
}
else {
legendtops.Text = CWRLocText.GetTextValue("Item_LegendOnMouseLang");
legendtops.OverrideColor = Color.Lerp(Color.BlueViolet, Color.Gold, 0.5f + (float)Math.Sin(Main.GlobalTimeWrappedHourly) * 0.5f);
}
}
}
public static void SafeLoadItem(int id) {
if (!Main.dedServ && id > 0 && id < TextureAssets.Item.Length && Main.Assets != null && TextureAssets.Item[id] != null) {
Main.instance.LoadItem(id);
}
}
public static void SafeLoadProj(int id) {
if (!Main.dedServ && id > 0 && id < TextureAssets.Projectile.Length && Main.Assets != null && TextureAssets.Projectile[id] != null) {
Main.instance.LoadProjectile(id);
}
}
public static int GetProjectileHasNum(int targetProjType, int ownerIndex = -1) {
int num = 0;
foreach (var proj in Main.ActiveProjectiles) {
if (ownerIndex >= 0 && ownerIndex != proj.owner) {
continue;
}
if (proj.type == targetProjType) {
num++;
}
}
return num;
}
public static int GetProjectileHasNum(this Player player, int targetProjType) => GetProjectileHasNum(targetProjType, player.whoAmI);
public static void ModifyLegendWeaponDamageFunc(Player player, Item item, int GetOnDamage, int GetStartDamage, ref StatModifier damage) {
float oldMultiplicative = damage.Multiplicative;
damage *= GetOnDamage / (float)GetStartDamage;
damage /= oldMultiplicative;
//首先,因为SD的运行优先级并不可靠,有的模组的修改在SD之后运行,比如炼狱模式,这个基础伤害缩放保证一些情况不会发生
damage *= GetStartDamage / (float)item.damage;
damage *= item.GetPrefixState().damageMult;
}
public static void ModifyLegendWeaponKnockbackFunc(Player player, Item item, float GetOnKnockback, float GetStartKnockback, ref StatModifier Knockback) {
Knockback *= GetOnKnockback / (float)GetStartKnockback;
//首先,因为SD的运行优先级并不可靠,有的模组的修改在SD之后运行,比如炼狱模式,这个基础击退缩放保证一些情况不会发生
Knockback *= GetStartKnockback / item.knockBack;
Knockback *= item.GetPrefixState().knockbackMult;
}
public static NPC FindNPCFromeType(int type) {
NPC npc = null;
foreach (var n in Main.npc) {
if (!n.active) {
continue;
}
if (n.type == type) {
npc = n;
}
}
return npc;
}
public static Recipe AddBlockingSynthesisEvent(this Recipe recipe) =>
recipe.AddConsumeItemCallback((Recipe recipe, int type, ref int amount) => { amount = 0; })
.AddOnCraftCallback(CWRRecipes.SpawnAction);
/// <summary>
/// 用于将一个武器设置为手持刀剑类,这个函数若要正确设置物品的近战属性,需要让其在初始化函数中最后调用
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="item"></param>
public static void SetKnifeHeld<T>(this Item item) where T : ModProjectile {
if (item.shoot == ProjectileID.None || !item.noUseGraphic
|| item.DamageType == ModContent.GetInstance<TrueMeleeDamageClass>()
|| item.DamageType == ModContent.GetInstance<TrueMeleeNoSpeedDamageClass>()) {
item.CWR().GetMeleePrefix = true;
}
item.noMelee = true;
item.noUseGraphic = true;
item.CWR().IsShootCountCorlUse = true;
item.shoot = ModContent.ProjectileType<T>();
if (item.shootSpeed <= 0) {
//不能让速度模场为0,这会让向量失去方向的性质,从而影响一些刀剑的方向判定
item.shootSpeed = 0.0001f;
}
}
/// <summary>
/// 快捷的将一个物品实例设置为手持对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="item"></param>
public static void SetHeldProj<T>(this Item item) where T : ModProjectile {
item.noUseGraphic = true;
item.CWR().hasHeldNoCanUseBool = true;
item.CWR().heldProjType = ModContent.ProjectileType<T>();
}
/// <summary>
/// 快捷的将一个物品实例设置为手持对象
/// </summary>
public static void SetHeldProj(this Item item, int id) {
item.noUseGraphic = true;
item.CWR().hasHeldNoCanUseBool = true;
item.CWR().heldProjType = id;
}
/// <summary>
/// 快捷的将一个物品实例设置为填装枪类实例
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="item"></param>
public static void SetCartridgeGun<T>(this Item item, int ammoCapacity = 1) where T : ModProjectile {
item.SetHeldProj<T>();
item.CWR().HasCartridgeHolder = true;
item.CWR().AmmoCapacity = ammoCapacity;
}
/// <summary>
/// 复制一个物品的属性
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="item"></param>
public static void SetItemCopySD<T>(this Item item) where T : ModItem => item.CloneDefaults(ModContent.ItemType<T>());
/// <summary>
/// 弹药是否应该被消耗,先行判断武器自带的消耗抵消比率,再在该基础上计算玩家的额外消耗抵消比率,比如弹药箱加成或者药水
/// </summary>
/// <param name="player"></param>
/// <param name="weapon"></param>
/// <returns></returns>
public static bool CanUseAmmoInWeaponShoot(this Player player, Item weapon) {
bool result = true;
if (weapon.type != ItemID.None) {
Item[] magazineContents = weapon.CWR().MagazineContents;
if (magazineContents.Length <= 0) {
return true;
}
result = ItemLoader.CanConsumeAmmo(weapon, magazineContents[0], player);
if (player.IsRangedAmmoFreeThisShot(magazineContents[0])) {
result = false;
}
}
return result;
}
/// <summary>
/// 判断该弹药物品是否应该被视为无限弹药
/// </summary>
/// <param name="ammoItem">要检查的弹药物品</param>
/// <returns>如果弹药物品是无限的,返回<see langword="true"/>;否则返回<see langword="false"/></returns>
public static bool IsAmmunitionUnlimited(Item ammoItem) {
bool result = !ammoItem.consumable;
if (CWRMod.Instance.luiafk != null || CWRMod.Instance.improveGame != null) {
if (ammoItem.stack >= 3996) {
result = true;
}
}
return result;
}
public static bool IsRangedAmmoFreeThisShot(this Player player, Item ammo) {
bool flag2 = false;
if (player.magicQuiver && ammo.ammo == AmmoID.Arrow && Main.rand.NextBool(5)) {
flag2 = true;
}
if (player.ammoBox && Main.rand.NextBool(5)) {
flag2 = true;
}
if (player.ammoPotion && Main.rand.NextBool(5)) {
flag2 = true;
}
if (player.huntressAmmoCost90 && Main.rand.NextBool(10)) {
flag2 = true;
}
if (player.chloroAmmoCost80 && Main.rand.NextBool(5)) {
flag2 = true;
}
if (player.ammoCost80 && Main.rand.NextBool(5)) {
flag2 = true;
}
if (player.ammoCost75 && Main.rand.NextBool(4)) {
flag2 = true;
}
return flag2;
}
/// <summary>
/// 赋予玩家无敌状态,这个函数与<see cref="Player.SetImmuneTimeForAllTypes(int)"/>类似
/// </summary>
/// <param name="player">要赋予无敌状态的玩家</param>
/// <param name="blink">是否允许玩家在无敌状态下闪烁默认为 false</param>
public static void GivePlayerImmuneState(this Player player, int time, bool blink = false) {
player.immuneNoBlink = !blink;
player.immune = true;
player.immuneTime = time;
for (int k = 0; k < player.hurtCooldowns.Length; k++) {
player.hurtCooldowns[k] = player.immuneTime;
}
}
/// <summary>
/// 将热键绑定的提示信息添加到 TooltipLine 列表中
/// </summary>
/// <param name="tooltips">要添加提示信息的 TooltipLine 列表</param>
/// <param name="mhk">Mod 热键绑定</param>
/// <param name="keyName">替换的关键字,默认为 "[KEY]"</param>
/// <param name="modName">Mod 的名称,默认为 "Terraria"</param>
public static void SetHotkey(this List<TooltipLine> tooltips, ModKeybind mhk, string keyName = "[KEY]", string modName = "Terraria") {
if (Main.dedServ || mhk is null) {
return;
}
string finalKey = mhk.TooltipHotkeyString();
tooltips.ReplaceTooltip(keyName, finalKey, modName);
}
/// <summary>
/// 替换 TooltipLine 列表中指定关键字的提示信息
/// </summary>
/// <param name="tooltips">要进行替换的 TooltipLine 列表</param>
/// <param name="targetKeyStr">要替换的关键字</param>
/// <param name="contentStr">替换后的内容</param>
/// <param name="modName">Mod 的名称,默认为 "Terraria"</param>
public static void ReplaceTooltip(this List<TooltipLine> tooltips, string targetKeyStr, string contentStr, string modName = "Terraria") {
TooltipLine line = tooltips.FirstOrDefault(x => x.Mod == modName && x.Text.Contains(targetKeyStr));
if (line != null) {
line.Text = line.Text.Replace(targetKeyStr, contentStr);
}
}
/// <summary>
/// 快速从模组本地化文件中设置对应物品的名称
/// </summary>
/// <param name="item"></param>
/// <param name="key"></param>
public static void EasySetLocalTextNameOverride(this Item item, string key) {
if (Main.GameModeInfo.IsJourneyMode) {
return;
}
item.SetNameOverride(Language.GetText($"Mods.CalamityOverhaul.Items.{key}.DisplayName").Value);
}
/// <summary>
/// 在游戏中发送文本消息
/// </summary>
/// <param name="message">要发送的消息文本</param>
/// <param name="colour">(可选)消息的颜色,默认为 null</param>
public static void Text(string message, Color? colour = null) {
Color newColor = (Color)(colour == null ? Color.White : colour);
if (Main.netMode == NetmodeID.Server) {
ChatHelper.BroadcastChatMessage(NetworkText.FromLiteral(message), (Color)(colour == null ? Color.White : colour));
return;
}
Main.NewText(message, newColor);