This commit is contained in:
enamoured_ committed 2025-03-01 13:44:29 -06:00
commit 2fa3c82b3d
41 files changed
+1112 -1013

No files matched your search

@@ -0,0 +1,86 @@
using CalamityMod.Particles;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.DataStructures;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Buffs.DamageOverTime
{
public class HadopelagicPressure : ModBuff
{
public override void SetStaticDefaults()
{
Main.debuff[Type] = true;
Main.pvpBuff[Type] = true;
Main.buffNoSave[Type] = true;
BuffID.Sets.LongerExpertDebuff[Type] = true;
}
public override void Update(Player player, ref int buffIndex)
{
player.Calamity().hPressure = true;
}
public override void Update(NPC npc, ref int buffIndex)
{
if (npc.Calamity().hPressure < npc.buffTime[buffIndex])
npc.Calamity().hPressure = npc.buffTime[buffIndex];
npc.DelBuff(buffIndex);
buffIndex--;
}
internal static void DrawEffects(PlayerDrawSet drawInfo)
{
Player Player = drawInfo.drawPlayer;
// Blue n black dust
Dust water = Dust.NewDustDirect(drawInfo.Position - new Vector2(2f), Player.width + 4, Player.height + 4, 390, Player.velocity.X * 0.4f, Player.velocity.Y * 0.4f, 100, default, 1.4f);
water.noGravity = true;
water.velocity *= 0.75f;
water.velocity.X *= 0.75f;
water.velocity.Y -= 1f;
if (Main.rand.NextBool(4))
{
water.noGravity = false;
water.scale *= 0.5f;
}
if (Main.rand.NextBool(4))
{
DirectionalPulseRing pulse = new DirectionalPulseRing(Player.Calamity().RandomDebuffVisualSpot, new Vector2(Main.rand.NextFloat(-1f, 1f), Main.rand.NextFloat(-3f, -4f)), Main.rand.NextBool() ? Color.DeepSkyBlue : Color.MediumBlue, new Vector2(0.8f, 1), 0, 0.09f, 0f, 45);
GeneralParticleHandler.SpawnParticle(pulse);
}
if (Main.rand.NextBool(10))
{
Color smokeColor = Color.MediumBlue;
Particle smoke = new HeavySmokeParticle(Player.Calamity().RandomDebuffVisualSpot, new Vector2(2f, 2f).RotatedByRandom(100) * Main.rand.NextFloat(0.3f, 0.7f), smokeColor, 40, Main.rand.NextFloat(0.3f, 0.4f), 0.5f, Main.rand.NextFloat(-0.2f, 0.2f), false, required: true);
GeneralParticleHandler.SpawnParticle(smoke);
}
}
internal static void DrawEffects(NPC npc, ref Color drawColor)
{
Vector2 npcSize = npc.Center + new Vector2(Main.rand.NextFloat(-npc.width / 2, npc.width / 2), Main.rand.NextFloat(-npc.height / 2, npc.height / 2));
if (Main.rand.NextBool(13))
{
Color smokeColor = Color.MediumBlue;
Particle smoke = new HeavySmokeParticle(npcSize, new Vector2(2f, 2f).RotatedByRandom(100) * Main.rand.NextFloat(0.3f, 0.7f), smokeColor, 40, Main.rand.NextFloat(0.3f, 0.4f) + (0.00000013f * npc.width * npc.height), 0.5f, Main.rand.NextFloat(-0.2f, 0.2f), false, required: true);
GeneralParticleHandler.SpawnParticle(smoke);
}
Dust water = Dust.NewDustDirect(npc.position - new Vector2(2f), npc.width + 4, npc.height + 4, 360, npc.velocity.X * 0.4f, npc.velocity.Y * 0.4f, 100, default, 1.4f);
water.noGravity = true;
water.velocity *= 0.75f;
water.velocity.X = water.velocity.X * 0.75f;
water.velocity.Y = water.velocity.Y - 1f;
if (Main.rand.NextBool(4))
{
water.noGravity = false;
water.scale *= 0.5f;
}
if (Main.rand.NextBool(6))
{
DirectionalPulseRing pulse = new DirectionalPulseRing(npcSize, new Vector2(Main.rand.NextFloat(-1f, 1f), Main.rand.NextFloat(-4.5f, -6f)), Main.rand.NextBool() ? Color.DeepSkyBlue : Color.MediumBlue, new Vector2(1f), 0, 0.12f + (0.0000007f * npc.width * npc.height), 0f, 35);
GeneralParticleHandler.SpawnParticle(pulse);
}
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 557 B

+6
View File
@@ -4,6 +4,9 @@ using System.Linq;
using CalamityMod.Balancing;
using CalamityMod.BiomeManagers;
using CalamityMod.Buffs;
using CalamityMod.Buffs.Alcohol;
using CalamityMod.Buffs.DamageOverTime;
using CalamityMod.Buffs.Placeables;
using CalamityMod.Buffs.StatBuffs;
using CalamityMod.Buffs.StatDebuffs;
using CalamityMod.CalPlayer.Dashes;
@@ -1227,6 +1230,7 @@ namespace CalamityMod.CalPlayer
public bool warped = false;
public bool cDepth = false;
public bool rTide = false;
public bool hPressure = false;
public bool fishAlert = false;
public bool clamity = false;
public bool NOU = false;
@@ -2415,6 +2419,7 @@ namespace CalamityMod.CalPlayer
warped = false;
cDepth = false;
rTide = false;
hPressure = false;
fishAlert = false;
clamity = false;
NOU = false;
@@ -2870,6 +2875,7 @@ namespace CalamityMod.CalPlayer
warped = false;
cDepth = false;
rTide = false;
hPressure = false;
fishAlert = false;
clamity = false;
NOU = false;
+6 -3
View File
@@ -263,6 +263,9 @@ namespace CalamityMod.CalPlayer
if (drawInfo.shadow == 0f && (calamityPlayer.hFlames || calamityPlayer.hInferno || calamityPlayer.banishingFire))
HolyFlames.DrawEffects(drawInfo);
if (calamityPlayer.hPressure && drawInfo.shadow == 0f)
HadopelagicPressure.DrawEffects(drawInfo);
// Icarus' Folly has visual effects but they are mutually exclusive with all Holy Flames variations to prevent visual clutter
else if (calamityPlayer.icarusFolly && drawInfo.shadow == 0f)
IcarusFolly.DrawEffects(drawInfo);
@@ -280,9 +283,6 @@ namespace CalamityMod.CalPlayer
if (calamityPlayer.nightwither && drawInfo.shadow == 0f) // Looks weaker if you have Moon Stone equipped
Nightwither.DrawEffects(drawInfo, reducedNightwitherDamage);
if (calamityPlayer.voidfrost && drawInfo.shadow == 0f)
Voidfrost.DrawEffects(drawInfo);
if (calamityPlayer.pFlames && drawInfo.shadow == 0f)
Plague.DrawEffects(drawInfo);
@@ -311,6 +311,9 @@ namespace CalamityMod.CalPlayer
if (calamityPlayer.vermillionFlux && drawInfo.shadow == 0f)
VermillionFlux.DrawEffects(drawInfo);
if (calamityPlayer.voidfrost && drawInfo.shadow == 0f)
Voidfrost.DrawEffects(drawInfo);
if (calamityPlayer.vHex && drawInfo.shadow == 0f)
VulnerabilityHex.DrawEffects(drawInfo);
#endregion
+4
View File
@@ -451,6 +451,10 @@ namespace CalamityMod.CalPlayer
{
damageSource = PlayerDeathReason.ByCustomReason(CalamityUtils.GetText("Status.Death.Riptide" + Main.rand.Next(1, 2 + 1)).Format(Player.name));
}
if (hPressure)
{
damageSource = PlayerDeathReason.ByCustomReason(CalamityUtils.GetText("Status.Death.HadopelagicPressure" + Main.rand.Next(1, 3 + 1)).Format(Player.name));
}
if (bFlames || weakBrimstoneFlames || demonicFlames)
{
damageSource = PlayerDeathReason.ByCustomReason(CalamityUtils.GetText("Status.Death.BrimstoneFlames" + Main.rand.Next(1, 3 + 1)).Format(Player.name));
+1
View File
@@ -120,6 +120,7 @@ namespace CalamityMod.CalPlayer
ApplyDoTDebuff(trueVHex, 50);
ApplyDoTDebuff(cDepth, 18, purity);
ApplyDoTDebuff(astralInfection, 24, infectedJewel || hideOfDeus || purity);
ApplyDoTDebuff(hPressure, 40, purity);
ApplyDoTDebuff(pFlames, alchFlask ? 10 : 30, purity);
ApplyDoTDebuff(cragsLava, 30);
ApplyDoTDebuff(shadowflame, 30, purity);
+9 -2
View File
@@ -2816,16 +2816,23 @@ namespace CalamityMod.CalPlayer
// Record the final breath loss rate for the stat meter
abyssBreathLossRateStat = (float)tick;
float resistanceSlowdownFactor = 1f;
// Reduce breath over ticks (frames)
abyssBreathCD++;
if (abyssBreathCD >= (int)tick)
abyssBreathCD++;
if (abyssBreathCD >= (int)(tick * resistanceSlowdownFactor))
{
// Reset modded breath variable
abyssBreathCD = 0;
// Reduce breath
if (Player.breath > 0)
{
Player.breath -= (int)(cDepth && !depthCharm ? breathLoss + 1D : breathLoss);
if (hPressure)
resistanceSlowdownFactor -= (int)(!abyssalDivingSuit ? 1.2f : 0.5f);
}
}
// If breath is greater than 0 and player has gills or is merfolk, balance out the effects by reducing breath
+1 -1
View File
@@ -1191,7 +1191,7 @@ namespace CalamityMod.CalPlayer
if (frostFlare)
CalamityUtils.Inflict246DebuffsNPC(target, BuffID.Frostburn2);
if (omegaBlueChestplate)
target.AddBuff(BuffType<CrushDepth>(), 180);
target.AddBuff(BuffType<HadopelagicPressure>(), 180);
if (sulphurSet)
target.AddBuff(BuffID.Poisoned, 60);
if (aSpark && Player.IsUnderwater())
@@ -1008,6 +1008,11 @@ GlacialState: {
Description: Cannot move
}
HadopelagicPressure: {
DisplayName: Hadopelagic Pressure
Description: Rapidly sinking to a watery grave
}
IcarusFolly: {
DisplayName: Icarus' Folly
Description:
@@ -34,6 +34,7 @@ AbyssalDivingSuit: {
Provides a moderate amount of light and reduces breath loss in the abyss
Abyss creatures are less likely to see you, mitigates the abyss' defense reduction, and lets you sink faster in liquids
Grants immunity to the sulphurous waters and Crush Depth's increased breath loss
Grants resistance to the increased breath loss caused by Hadopelagic Pressure
'''
}
@@ -369,7 +369,7 @@ OmegaBlueChestplate: {
Tooltip:
'''
12% increased damage and 8% increased critical strike chance
Your attacks inflict Crush Depth
Your attacks inflict Hadopelagic Pressure
No positive life regen
'''
}
@@ -52,6 +52,9 @@ CorpusAvertor: "{0} became the Blood God's sacrifice."
CrushDepth1: "{0} was crushed by the pressure."
CrushDepth2: "{0}'s lungs collapsed."
CrushDepth3: "{0}'s bones crunched under the deep pressure."
HadopelagicPressure1: "{0} was crushed in the lightless void."
HadopelagicPressure2: "{0} was reduced to a smear of waterlogged paste."
HadopelagicPressure3: "{0} suffered a critical pressurization event."
Daybroken: "{0} was incinerated by solar rays."
Dragonfire1: "{0}'s ashes scatter in the wind."
Dragonfire2: "{0}'s embers fade away in a warm glow."
+1 -1
View File
@@ -256,7 +256,7 @@ namespace CalamityMod.NPCs.Abyss
public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo)
{
if (hurtInfo.Damage > 0)
target.AddBuff(ModContent.BuffType<CrushDepth>(), 300, true);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 300, true);
}
public override void ModifyNPCLoot(NPCLoot npcLoot)
+1 -1
View File
@@ -624,7 +624,7 @@ namespace CalamityMod.NPCs.Abyss
public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo)
{
if (hurtInfo.Damage > 0)
target.AddBuff(ModContent.BuffType<CrushDepth>(), 300, true);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 300, true);
}
public override void ModifyNPCLoot(NPCLoot npcLoot)
+1 -1
View File
@@ -512,7 +512,7 @@ namespace CalamityMod.NPCs.Abyss
public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo)
{
if (hurtInfo.Damage > 0)
target.AddBuff(ModContent.BuffType<CrushDepth>(), 300, true);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 300, true);
}
}
}
+1 -1
View File
@@ -364,7 +364,7 @@ namespace CalamityMod.NPCs.Abyss
public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo)
{
if (hurtInfo.Damage > 0)
target.AddBuff(ModContent.BuffType<RiptideDebuff>(), 90);
target.AddBuff(ModContent.BuffType<CrushDepth>(), 90);
}
public override bool PreDraw(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor)
+1 -1
View File
@@ -709,7 +709,7 @@ namespace CalamityMod.NPCs.Abyss
public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo)
{
if (hurtInfo.Damage > 0)
target.AddBuff(ModContent.BuffType<CrushDepth>(), 300, true);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 300, true);
}
public override float SpawnChance(NPCSpawnInfo spawnInfo)
+15
View File
@@ -359,6 +359,7 @@ namespace CalamityMod.NPCs
public int cDepth = 0;
public int rTide = 0;
public int hPressure = 0;
public int gsInferno = 0;
public int dragonFire = 0;
public int vermillionFlux = 0;
@@ -610,6 +611,7 @@ namespace CalamityMod.NPCs
myClone.cDepth = cDepth;
myClone.rTide = rTide;
myClone.hPressure = hPressure;
myClone.gsInferno = gsInferno;
myClone.miracleBlight = miracleBlight;
myClone.dragonFire = dragonFire;
@@ -1272,6 +1274,13 @@ namespace CalamityMod.NPCs
int baseCrushDepthDoTValue = (int)(100 * waterDamageMult);
ApplyDPSDebuff(baseCrushDepthDoTValue, baseCrushDepthDoTValue / 2, ref npc.lifeRegen, ref damage);
}
//Hadopelagic Pressure
if (hPressure > 0)
{
int baseHadopelagicPressureDoTValue = (int)(400 * waterDamageMult);
ApplyDPSDebuff(baseHadopelagicPressureDoTValue, baseHadopelagicPressureDoTValue / 2, ref npc.lifeRegen, ref damage);
}
#endregion
if (npc.dryadBane)
@@ -5639,6 +5648,8 @@ namespace CalamityMod.NPCs
crumble--;
if (cDepth > 0)
cDepth--;
if (hPressure > 0)
hPressure--;
if (rTide > 0)
rTide--;
if (gsInferno > 0)
@@ -7198,6 +7209,9 @@ namespace CalamityMod.NPCs
if (cDepth > 0)
CrushDepth.DrawEffects(npc, ref drawColor);
if (hPressure > 0)
HadopelagicPressure.DrawEffects(npc, ref drawColor);
if (dragonFire > 0)
Dragonfire.DrawEffects(npc, ref drawColor);
@@ -7414,6 +7428,7 @@ namespace CalamityMod.NPCs
("CalamityMod/Buffs/DamageOverTime/Dragonfire", NPC => NPC.Calamity().dragonFire > 0),
("CalamityMod/Buffs/DamageOverTime/ElementalMix", NPC => NPC.Calamity().elementalMix > 0),
("CalamityMod/Buffs/DamageOverTime/GodSlayerInferno", NPC => NPC.Calamity().gsInferno > 0),
("CalamityMod/Buffs/DamageOverTime/HadopelagicPressure", NPC => NPC.Calamity().hPressure > 0),
("CalamityMod/Buffs/DamageOverTime/HolyFlames", NPC => NPC.Calamity().hFlames > 0),
("CalamityMod/Buffs/DamageOverTime/Laceration", NPC => NPC.Calamity().laceration > 0),
("CalamityMod/Buffs/DamageOverTime/HeavyBleeding", NPC => NPC.Calamity().heavybleeding > 0),
+36 -14
View File
@@ -221,9 +221,11 @@ namespace CalamityMod.NPCs
// Sand Elemental
// Elemental in a Bottle @ 20% Normal, 33.33% Expert+
// Rare Elemental in a Bottle @ 10% Normal, 16.67% Expert+
// Desert Key @ 10%
case NPCID.SandElemental:
npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType<WifeinaBottle>(), 5, 3));
npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType<WifeinaBottlewithBoobs>(), 10, 6));
npcLoot.Add(ItemID.DungeonDesertKey, 10);
break;
#endregion
@@ -302,8 +304,10 @@ namespace CalamityMod.NPCs
// Ice Golem
// 8-10 Essence of Eleum @ 100%, 10-12 Expert+
// Frozen Key @ 10%
case NPCID.IceGolem:
npcLoot.Add(DropHelper.NormalVsExpertQuantity(ModContent.ItemType<EssenceofEleum>(), 1, 8, 10, 10, 12));
npcLoot.Add(ItemID.FrozenKey, 10);
break;
#endregion
@@ -363,13 +367,27 @@ namespace CalamityMod.NPCs
npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType<IchorSpear>(), 25, 15));
break;
// Biome Mimics
// Corrupt Mimic
// Celestial Claymore @ 14.29% Normal, 25% Expert+
case NPCID.BigMimicHallow:
case NPCID.BigMimicCorruption:
case NPCID.BigMimicCrimson:
case NPCID.BigMimicJungle:
npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType<CelestialClaymore>(), 7, 4));
npcLoot.Add(ItemID.CorruptionKey, 10);
break;
// Crimson Mimic
// Celestial Claymore @ 14.29% Normal, 25% Expert+
// Crimson Key @ 10%
case NPCID.BigMimicCrimson:
npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType<CelestialClaymore>(), 7, 4));
npcLoot.Add(ItemID.CrimsonKey, 10);
break;
// Hallowed Mimic
// Celestial Claymore @ 14.29% Normal, 25% Expert+
// Hallowed Key @ 10%
case NPCID.BigMimicHallow:
npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType<CelestialClaymore>(), 7, 4));
npcLoot.Add(ItemID.HallowedKey, 10);
break;
// World Feeder
@@ -411,6 +429,20 @@ namespace CalamityMod.NPCs
case NPCID.Moth:
npcLoot.ChangeDropRate(ItemID.ButterflyDust, 1, 1);
break;
// Jungle Mimic
// Celestial Claymore @ 14.29% Normal, 25% Expert+
case NPCID.BigMimicJungle:
npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType<CelestialClaymore>(), 7, 4));
break;
// Lihzahrd + Flying Snake
// Jungle Key @ 0.67%
case NPCID.Lihzahrd:
case NPCID.LihzahrdCrawler:
case NPCID.FlyingSnake:
npcLoot.Add(ItemID.JungleKey, 150);
break;
#endregion
#region Dungeon
@@ -1222,10 +1254,6 @@ namespace CalamityMod.NPCs
// Would be in the bag otherwise
npcLoot.AddNormalOnly(ModContent.ItemType<ThankYouPainting>(), ThankYouPainting.DropInt);
// WoF drops Evil Keys
npcLoot.Add(ItemID.CorruptionKey, 3);
npcLoot.Add(ItemID.CrimsonKey, 3);
// Master items drop in Revengeance
rev.Add(ItemID.WallofFleshMasterTrophy);
rev.Add(ItemID.WallOfFleshGoatMountItem, 4);
@@ -1248,9 +1276,6 @@ namespace CalamityMod.NPCs
// Would be in the bag otherwise
npcLoot.AddNormalOnly(ModContent.ItemType<ThankYouPainting>(), ThankYouPainting.DropInt);
// Queen Slime drops the Hallowed Key
npcLoot.Add(ItemID.HallowedKey, 3);
// Master items drop in Revengeance
rev.Add(ItemID.QueenSlimeMasterTrophy);
rev.Add(ItemID.QueenSlimePetItem, 4);
@@ -1404,9 +1429,6 @@ namespace CalamityMod.NPCs
npcLoot.AddNormalOnly(DropHelper.PerPlayer(ModContent.ItemType<LivingShard>(), 1, 25, 30));
npcLoot.AddNormalOnly(ModContent.ItemType<ThankYouPainting>(), ThankYouPainting.DropInt);
// Plantera drops Jungle Key
npcLoot.Add(ItemID.JungleKey, 3);
// Master items drop in Revengeance
rev.Add(ItemID.PlanteraMasterTrophy);
rev.Add(ItemID.PlanteraPetItem, 4);
-2
View File
@@ -1428,8 +1428,6 @@ namespace CalamityMod.NPCs.Cryogen
normalOnly.Add(ModContent.ItemType<FrostFlare>(), DropHelper.NormalWeaponDropRateFraction);
}
npcLoot.Add(ItemID.FrozenKey, 3);
// Trophy (always directly from boss, never in bag)
npcLoot.Add(ModContent.ItemType<CryogenTrophy>(), 10);
-3
View File
@@ -677,9 +677,6 @@ IL_6899:
{
npcLoot.Add(ItemID.AncientBattleArmorMaterial);
// Great Sand Shark drops the Desert Key
npcLoot.Add(ItemID.DungeonDesertKey, 3);
// 1 Grand Scale guaranteed; on Expert, 33% chance of getting a second one
npcLoot.Add(ModContent.ItemType<GrandScale>());
npcLoot.AddIf(() => Main.expertMode, ModContent.ItemType<GrandScale>(), 3);
+1 -1
View File
@@ -1519,7 +1519,7 @@ namespace CalamityMod.NPCs.PrimordialWyrm
public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo)
{
if (NPC.Opacity == 1f && hurtInfo.Damage > 0)
target.AddBuff(ModContent.BuffType<CrushDepth>(), 1200, true);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 1200, true);
}
}
}
+240 -139
View File
@@ -1,53 +1,50 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Linq;
using System.Threading;
using CalamityMod.Enums;
using CalamityMod.Particles;
using CalamityMod.Items.Placeables.Banners;
using CalamityMod.Tiles;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.DataStructures;
using Terraria.GameContent;
using Terraria.ID;
using Terraria.Utilities;
using Terraria.ModLoader;
using static CalamityMod.CalamityUtils;
using static Terraria.ModLoader.ModContent;
namespace CalamityMod.NPCs.SunkenSea
{
public class Probesnout : SunkenSeaNPC
public class Probesnout : SunkenSeaNPC, IPathFinder
{
public static float PathDetectionSize = 300f;
private static Task<List<Vector2>> _pathfindingTask;
#region Members
protected override List<int> HuntNPCs => new()
{
// NPCType<Slugbun>(),
};
public static int IdleRandomMovementUnlikeliness = 250;
public static int IdleMinPathDistance = 200;
public static int IdleMaxPathDistance = 400;
protected override List<int> AvoidNPCs => new()
{
public static int FleeTileAnticipationDistance = 5 * 16;
public static int FleeMinPathDistance = 80;
public static int FleeMaxPathDistance = 160;
protected override List<int> PreyIDs =>
[
// NPCType<Slugbun>(),
];
protected override List<int> PredatorIDs =>
[
// NPCType<IlmerianAxolotl>(),
NPCType<Sharkoon>(),
// NPCType<Polyperil>(),
// NPCType<CrestedStalker>(),
// NPCType<Hermititan>(),
};
];
private enum PersonalityType { Curious, Shy, Paranoid }
private PersonalityType Personality
{
get => (PersonalityType)NPC.ai[0];
set
{
NPC.ai[0] = (float)value;
NetUpdate();
}
}
private enum AnimationState { Idle, Attack }
private enum AnimationState { Idle, Eating }
private AnimationState Animation
{
@@ -66,166 +63,170 @@ namespace CalamityMod.NPCs.SunkenSea
AnimationFrames = 8;
TimePerAnimationFrame = 5;
break;
case AnimationState.Attack:
case AnimationState.Eating:
AnimationFrames = 12;
TimePerAnimationFrame = 7;
break;
}
NPC.ai[1] = (float)value;
NetUpdate();
}
}
protected override SunkenSeaBiomeFlags BiomeDesignation => SunkenSeaBiomeFlags.RadiantReefs;
protected override float SpawningChance => 0f;
private int AnimationFrames = 8;
private int TimePerAnimationFrame = 5;
private float MaximumSpeed = 6f;
private Vector2 ScaleSquish = Vector2.One;
private Action _currentBehavior;
private Action CurrentBehavior
{
get => _currentBehavior;
set
{
_previousBehavior = _currentBehavior;
_currentBehavior = value;
}
}
private Action _previousBehavior;
public PathfindingTask Path { get; set; }
public Vector2 Position => NPC.Center;
public Vector2 Velocity { get => NPC.velocity; set => NPC.velocity = value; }
public float Acceleration => 0.4f;
public float MaxSpeed => 8f;
private Vector2 SpongeFoundPosition;
private bool HasEatenSponge;
#endregion
#region AI
protected override void BehaviorOnSpawn()
protected override bool PlayerSearchFilter(Player p)
{
CurrentBehavior = IdleBehavior;
return base.PlayerSearchFilter(p) || p == CurrentPlayer && Vector2.DistanceSquared(NPC.Center, p.Center) < 960f * 960f;
}
WeightedRandom<PersonalityType> randomPersonality = new();
randomPersonality.Add(PersonalityType.Curious, 0.6f);
randomPersonality.Add(PersonalityType.Shy, 0.3f);
randomPersonality.Add(PersonalityType.Paranoid, 0.1f);
Personality = randomPersonality.Get();
protected override bool NPCSearchFilter(NPC n)
{
return base.NPCSearchFilter(n) || (n == CurrentPrey || n == CurrentPredator) && Vector2.DistanceSquared(NPC.Center, n.Center) < 960f * 960f;
}
public override void OnSpawn(IEntitySource source)
{
CurrentBehavior = IdlingBehavior;
NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt();
NPC.GravityMultiplier *= 2f;
NPC.MaxFallSpeedMultiplier *= 2f;
}
protected override void CreatureAI()
public override void AI()
{
CurrentBehavior.Invoke();
CurrentBehavior?.Invoke();
if (!NPC.velocity.HasNaNs())
ConeDetectionDirection = (NPC.rotation * MathF.Sign(NPC.velocity.Y) + (NPC.spriteDirection == -1 ? MathHelper.Pi : 0f)).ToRotationVector2();
NPC.rotation = MathHelper.ToRadians(NPC.velocity.Length() * 3f) * MathF.Sign(NPC.velocity.X);
if (MathF.Abs(NPC.velocity.X) > 2f)
NPC.rotation = MathHelper.ToRadians(NPC.velocity.X * 3f);
if (CurrentBehavior == EatingBehavior && Vector2.DistanceSquared(NPC.Center, SpongeFoundPosition) <= 64f * 64f)
NPC.spriteDirection = NPC.direction = MathF.Sign(SpongeFoundPosition.X - NPC.Center.X);
else if (NPC.velocity.LengthSquared() != 0f)
NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X);
if (!NPC.wet)
CurrentBehavior = OutsideWaterBehavior;
if (Main.rand.NextBool(50) && !HasEatenSponge && CurrentBehavior == IdlingBehavior)
ThreadPool.QueueUserWorkItem(_ => DetectSponges(), null);
if (NPC.velocity.LengthSquared() > MaximumSpeed * MaximumSpeed)
NPC.velocity = NPC.velocity.SafeNormalize(-Vector2.UnitY) * MaximumSpeed;
if (!NPC.wet && CurrentBehavior != OutsideWaterBehavior)
{
NPC.noGravity = false;
CurrentBehavior = OutsideWaterBehavior;
}
if (ScaleSquish.Y > 1f)
ScaleSquish.Y -= 0.025f;
if (ScaleSquish.Y < 1f)
ScaleSquish.Y = 1f;
ScaleSquish.Y = Math.Max(1f, ScaleSquish.Y - 0.025f);
}
protected override void OnBehaviorChange(Action newBehavior) => NPC.noGravity = newBehavior != OutsideWaterBehavior;
protected override void OnPreyDetection(NPC prey)
{
// If it's not a small fish and it's not being chased by a predator, the Probesnout may hunt.
if (CurrentPredator is null)
{
CurrentBehavior = HuntBehavior;
React(Color.Orange * 0.6f, EmoteExpressionParticle.EmoteType.Exclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f });
}
if (CurrentPredator != null)
return;
ScaleSquish.Y += 1.4f;
CurrentBehavior = HuntBehavior;
ScaleSquish.Y += 0.4f;
}
protected override void OnPredatorDetection(NPC predator)
{
// Regardless of anything, if it detects a predator, time to run.
CurrentBehavior = AvoidBehavior;
React(Color.Red * 0.6f, EmoteExpressionParticle.EmoteType.DoubleExclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f });
ScaleSquish.Y += 1.4f;
CurrentBehavior = FleeingBehavior;
ScaleSquish.Y += 0.4f;
}
protected override void OnPlayerDetection(Player player)
{
// If the Probesnout is shy, it'll run away from the player.
if (Personality == PersonalityType.Shy)
{
CurrentBehavior = AvoidBehavior;
React(Color.Orange, EmoteExpressionParticle.EmoteType.QuestionExclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f });
}
if (Personality == PersonalityType.Curious)
React(Color.Green, EmoteExpressionParticle.EmoteType.Question, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f });
if (CurrentPredator != null)
return;
ScaleSquish.Y += 0.4f;
}
private void IdleBehavior()
private void IdlingBehavior()
{
if (_pathfindingTask.Result == null)
// At random, the mob will choose a random nearby point and pathfind there.
PathfindingTask parameters = null;
if (Main.rand.NextBool(150))
{
NPC.velocity *= 0.95f;
if (Main.rand.NextBool(125))
_pathfindingTask = CalamityUtils.FindPathAsync(new(
NPC.Center,
NPC.Center + Main.rand.NextVector2CircularEdge(PathDetectionSize, PathDetectionSize) * Main.rand.NextFloat(0.75f, 1f),
SunkenSeaTileValidity));
_randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * 300f;
NPC.netUpdate = true;
parameters = new PathfindingTask(NPC.Center, _randomPathPoint, SunkenSeaTileValidity);
}
else
GenericPathFollowing(acceleration: 0.03f);
this.DoPathfinding(parameters);
}
private void AvoidBehavior()
private void FleeingBehavior()
{
// Depending on the personality, the Sharkoon will choose who to avoid.
Entity entityToAvoid = null;
switch (Personality)
// If the avoided entity is gone, go back to idling.
if (CurrentPredator == null)
{
case PersonalityType.Shy:
entityToAvoid = (NearestEntity is NPC nearestNPC && HuntNPCs.Contains(nearestNPC.type)) ? null : NearestEntity;
break;
case PersonalityType.Curious:
entityToAvoid = CurrentPredator;
break;
case PersonalityType.Paranoid:
entityToAvoid = CurrentPredator;
break;
}
// If there aren't any more targets detected, go back to idling.
if (entityToAvoid is null)
{
CurrentBehavior = IdleBehavior;
CurrentBehavior = IdlingBehavior;
return;
}
bool isAvoidingPredator = entityToAvoid is NPC npc && npc.whoAmI == CurrentPredator.whoAmI;
// While it doesn't have any obstacles in front of it, run away in a straight line.
// Try to manuever if there are any obstacles.
var headedDirection = CurrentPredator.DirectionTo(NPC.Center) * 200f;
// bool tileNotWater = GetIntersectingPoints(NPC.Center, NPC.Center + headedDirection).Any(point => Main.tile[point].IsTileSolid() || Main.tile[point].LiquidAmount < 255);
if (HasPath)
if (false)
{
float fleeingDistance = isAvoidingPredator ? 600f : 300f;
Vector2 randomEscapePoint = NPC.Center + NPC.DirectionFrom(entityToAvoid.Center).RotatedByRandom(MathHelper.PiOver2) * Main.rand.NextFloat(fleeingDistance, fleeingDistance + 100f);
while (Main.tile[randomEscapePoint.ToTileCoordinates()].IsTileSolid())
randomEscapePoint = NPC.Center + NPC.DirectionFrom(entityToAvoid.Center).RotatedByRandom(MathHelper.PiOver2) * Main.rand.NextFloat(fleeingDistance, fleeingDistance + 100f);
do
{
var randomNormalDirection = headedDirection.RotatedBy(MathHelper.PiOver2 * Main.rand.NextBool().ToDirectionInt());
_randomPathPoint = randomNormalDirection.RotatedByRandom(MathHelper.PiOver4);
if (!Main.tile[(NPC.Center + _randomPathPoint).ToTileCoordinates()].IsTileSolid())
break;
}
while (!Main.tile[(NPC.Center + _randomPathPoint).ToTileCoordinates()].IsTileSolid());
NPC.netUpdate = true;
this.DoPathfinding(new PathfindingTask(NPC.Center, NPC.Center + _randomPathPoint, SunkenSeaTileValidity));
}
else
GenericPathFollowing(acceleration: 0.14f);
{
NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration;
Path = null;
// Cap the speed if MaxSpeed has been surpassed.
if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed;
}
}
private void HuntBehavior()
@@ -233,25 +234,110 @@ namespace CalamityMod.NPCs.SunkenSea
// If there's no more prey, go back to idling.
if (CurrentPrey is null)
{
CurrentBehavior = IdleBehavior;
CurrentBehavior = IdlingBehavior;
return;
}
if (!HasLineOfSight(CurrentPrey.Center))
// With sight, just go straight at him. Without it, try to pathfind over them.
this.DoPathfinding(new PathfindingTask(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity), continuouslyUpdatePath: true);
}
private void EatingBehavior()
{
if (Vector2.DistanceSquared(NPC.Center, SpongeFoundPosition) <= 64f * 64f)
{
if (HasPath)
GenericPathFollowing(acceleration: 0.14f);
else
_pathfindingTask = CalamityUtils.FindPathAsync(new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity));
NPC.velocity *= 0.9f;
Animation = AnimationState.Eating;
if (NPC.frame.Y >= NPC.height * AnimationFrames)
{
HasEatenSponge = true;
Animation = AnimationState.Idle;
CurrentBehavior = IdlingBehavior;
return;
}
}
else
NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * 0.14f;
this.DoPathfinding(new PathfindingTask(NPC.Center, SpongeFoundPosition, SunkenSeaTileValidity));
}
private void OutsideWaterBehavior()
{
if (NPC.wet)
CurrentBehavior = PreviousBehavior;
{
NPC.noGravity = true;
CurrentBehavior = _previousBehavior;
}
}
private void DetectSponges()
{
Vector2? closestSpongeFound = null;
float closestDistanceSquared = float.MaxValue;
foreach (var direction in Directions)
{
// var points = GetIntersectingPoints(NPC.Center, NPC.Center + direction * 360f);
var points = new Point[1];
foreach (var point in points)
{
// Check if the tile coordinates are within the valid range
if (!WorldGen.InWorld(point.X, point.Y))
continue;
// Check if the current tile is AerialiteBrick
if (Main.tile[point].TileType == TileType<AerialiteBrick>())
{
// Check all adjacent directions for a non-solid tile with line of sight
foreach (var adjacentDirection in Directions)
{
Point adjacentPoint = point + adjacentDirection.ToPoint();
// Validate adjacent tile coordinates
if (!WorldGen.InWorld(adjacentPoint.X, adjacentPoint.Y))
continue;
// Skip if the adjacent tile is solid
if (Main.tile[adjacentPoint].IsTileSolid())
continue;
Vector2 worldPos = adjacentPoint.ToWorldCoordinates();
if (NPC.HasSight(worldPos))
{
// Calculate the squared distance from NPC to the adjacent tile
float distanceSquared = Vector2.DistanceSquared(NPC.Center, worldPos);
if (distanceSquared < closestDistanceSquared)
{
closestDistanceSquared = distanceSquared;
closestSpongeFound = worldPos;
}
}
}
// Break after checking the first sponge nutrient in this direction
break;
}
}
}
// Update behavior if a valid tile was found
if (closestSpongeFound.HasValue)
{
CurrentBehavior = EatingBehavior;
SpongeFoundPosition = closestSpongeFound.Value;
}
}
public override void HitEffect(NPC.HitInfo hit)
{
for (int k = 0; k < 25; k++)
{
Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.Blood, hit.HitDirection, -1f, 0, default, 1f);
}
if (NPC.life <= 0)
{
for (int i = 0; i < 4; i++)
Gore.NewGoreDirect(NPC.GetSource_Death(), NPC.Center, new Vector2(hit.HitDirection, -1f), Mod.Find<ModGore>($"{Name}{i + 1}").Type);
}
}
#endregion
@@ -265,8 +351,9 @@ namespace CalamityMod.NPCs.SunkenSea
{
NPC.frame.Y += frameHeight;
NPC.frame.Y = Math.Min(NPC.frame.Y, AnimationFrames * frameHeight);
NPC.frame.Y = NPC.frame.Y % (AnimationFrames * frameHeight);
NPC.frameCounter = 0;
if (Animation == AnimationState.Idle)
NPC.frame.Y %= AnimationFrames * frameHeight;
}
}
@@ -290,7 +377,7 @@ namespace CalamityMod.NPCs.SunkenSea
public override void SetStaticDefaults()
{
base.SetStaticDefaults();
Main.npcFrameCount[Type] = 15;
Main.npcFrameCount[Type] = 12;
Main.npcCatchable[Type] = true;
NPCID.Sets.CountsAsCritter[Type] = true;
}
@@ -298,35 +385,42 @@ namespace CalamityMod.NPCs.SunkenSea
public override void SetDefaults()
{
base.SetDefaults();
// BannerItem = ItemType<ProbesnoutBanner>();
NPC.lifeMax = 5;
NPC.aiStyle = -1;
AIType = -1;
NPC.npcSlots = 0.1f;
NPC.noGravity = true;
NPC.chaseable = false;
NPC.width = 44;
NPC.height = 55;
NPC.height = 50;
NPC.HitSound = SoundID.NPCHit1;
NPC.DeathSound = SoundID.NPCDeath1;
NPC.value = Item.buyPrice(0, 0, 5, 0);
NPC.Calamity().VulnerableToHeat = false;
NPC.Calamity().VulnerableToSickness = true;
NPC.Calamity().VulnerableToElectricity = true;
NPC.Calamity().VulnerableToWater = false;
}
#endregion
#region Syncing
private Vector2 _randomPathPoint;
public override void SendExtraAI(BinaryWriter writer)
{
base.SendExtraAI(writer);
writer.Write7BitEncodedInt(AnimationFrames);
writer.Write7BitEncodedInt(TimePerAnimationFrame);
writer.WriteVector2(_randomPathPoint);
}
public override void ReceiveExtraAI(BinaryReader reader)
{
base.ReceiveExtraAI(reader);
AnimationFrames = reader.Read7BitEncodedInt();
TimePerAnimationFrame = reader.Read7BitEncodedInt();
_randomPathPoint = reader.ReadVector2();
}
#endregion
@@ -348,8 +442,15 @@ namespace CalamityMod.NPCs.SunkenSea
public override void HitEffect(NPC.HitInfo hit)
{
for (int i = 0; i < 5; i++)
Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.GoldCritter, hit.HitDirection, -1f);
for (int k = 0; k < 25; k++)
{
Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.GoldCritter, hit.HitDirection, -1f, 0, default, 1f);
}
if (NPC.life <= 0)
{
for (int i = 0; i < 4; i++)
Gore.NewGoreDirect(NPC.GetSource_Death(), NPC.Center, new Vector2(hit.HitDirection, -1f), Mod.Find<ModGore>($"{Name}{i + 1}").Type);
}
}
}
}
+247 -325
View File
@@ -1,69 +1,43 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using CalamityMod.Enums;
using CalamityMod.Items.Placeables.Banners;
using CalamityMod.Particles;
using CalamityMod.Projectiles.Enemy;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.Audio;
using Terraria.DataStructures;
using Terraria.GameContent;
using Terraria.GameContent.UI.Elements;
using Terraria.ID;
using Terraria.ModLoader.Utilities;
using Terraria.Utilities;
using Terraria.ModLoader;
using static CalamityMod.CalamityUtils;
using static Terraria.ModLoader.ModContent;
namespace CalamityMod.NPCs.SunkenSea
{
public class Sharkoon : SunkenSeaNPC
public class Sharkoon : SunkenSeaNPC, IPathFinder
{
public static float DistanceToKaboom = 80f;
public static float IdleMovementMaxRange = 300f;
public static int ExplosionRadius = 80;
public static float TimeToRecover = 600f;
public static float TimeRecovering = 120f;
private Task<List<Vector2>> _pathfindingTask = null;
#region Fields & Properties
protected override List<int> HuntNPCs => new()
{
// NPCType<GildedAxolotl>(),
NPCType<SeaFloaty>(),
NPCType<Probesnout>(),
NPCType<SeaMinnow>(),
NPCType<EutrophicRay>(),
};
#region Static Fields
protected override List<int> AvoidNPCs => new()
{
// NPCType<Polyperil>(),
// NPCType<Snailord>(),
NPCType<PrismBack>(),
// NPCType<Hermititan>,
};
public static int IdleRandomMovementUnlikeliness = 250;
public static int IdleMinPathDistance = 200;
public static int IdleMaxPathDistance = 400;
/// <summary>
/// The different types of personality this NPC can have.
/// </summary>
private enum PersonalityType { Shy, Curious, Paranoid }
public static int FleeTileAnticipationDistance = 64;
public static int FleeMinPathDistance = 80;
public static int FleeMaxPathDistance = 160;
/// <summary>
/// The current personality of this NPC.
/// </summary>
private PersonalityType Personality
{
get => (PersonalityType)NPC.ai[0];
set
{
NPC.ai[0] = (float)value;
NetUpdate();
}
}
public static int ExplosionDistance = 80;
public static int ExplosionRadius = 80;
public static int ExplosionCooldown = 600;
public static int RecoveringTime = 120;
#endregion
/// <summary>
/// The different types of animation this enemy can have.
@@ -101,8 +75,6 @@ namespace CalamityMod.NPCs.SunkenSea
ChangeAnimation(animationFrames: 6, timePerAnimationFrame: 6, loops: true);
break;
}
NetUpdate();
}
}
@@ -110,63 +82,98 @@ namespace CalamityMod.NPCs.SunkenSea
/// The amount of frames that one column of sprites has.<br/>
/// Defaults to 7 since that's the first column's amount of frames.
/// </summary>
private int AnimationFrames = 7;
private int _animationFrames = 7;
/// <summary>
/// The amount, in frames, that it takes to go to the next animation frame.<br/>
/// Defaults to 7.
/// </summary>
private int TimePerAnimationFrame = 7;
private int _timePerAnimationFrame = 7;
/// <summary>
/// Whether or not the animation loops or not.<br/>
/// Defaults to <see langword="true"/>.
/// </summary>
private bool AnimationLoop = true;
private bool _animationLoop = true;
/// <summary>
/// The squish of this NPC while drawing.
/// </summary>
private Vector2 _scaleSquish = Vector2.One;
private Entity _avoidedEntity;
/// <summary>
/// A timer used to know when the NPC should recover after it explodes.
/// </summary>
private ref float RecoverTimer => ref NPC.ai[2];
/// <summary>
/// The maximum speed this NPC can have, it cannot be faster than this number.
/// </summary>
private float MaximumSpeed = 4f;
/// <summary>
/// The acceleration of the Sharkoon.
/// </summary>
private const float Acceleration = 0.25f;
/// <summary>
/// How unlikely is the Sharkoon going to move normally.<br/>
/// Defaults to 250.
/// </summary>
private int RandomIdleMovementUnlikeliness = 250;
/// <summary>
/// Whether or not the Sharkoon is capable of exploding.
/// </summary>
private bool IsBig => Animation == AnimationState.Normal;
private bool CanExplode => Animation == AnimationState.Normal;
/// <summary>
/// Whether or not the Sharkoon is currently exploding.
/// </summary>
private bool IsExploding => CurrentBehavior == ExplodingBehavior;
private Action _currentBehavior;
private Action CurrentBehavior
{
get => _currentBehavior;
set
{
if (value != _currentBehavior)
OnBehaviorChange(value);
_previousBehavior = _currentBehavior;
_currentBehavior = value;
}
}
private Action _previousBehavior;
#region SunkenSeaNPC Implementation
protected override List<int> PreyIDs =>
[
// NPCType<GildedAxolotl>(),
NPCType<SeaFloaty>(),
NPCType<Probesnout>(),
NPCType<ProbesnoutGold>(),
NPCType<SeaMinnow>(),
NPCType<EutrophicRay>(),
];
protected override List<int> PredatorIDs =>
[
// NPCType<Polyperil>(),
// NPCType<Snailord>(),
NPCType<PrismBack>(),
// NPCType<Hermititan>,
];
protected override SunkenSeaBiomeFlags BiomeDesignation => SunkenSeaBiomeFlags.RadiantReefs;
protected override float SpawningChance => SpawnCondition.CaveJellyfish.Chance * 0.9f;
/// <summary>
/// The squish of this NPC while drawing.
/// </summary>
private Vector2 ScaleSquish = Vector2.One;
#endregion
#region Other Overridden Methods
#region IPathFinder Implementation
public PathfindingTask Path { get; set; }
public Vector2 Position => NPC.Center;
public Vector2 Velocity { get => NPC.velocity; set => NPC.velocity = value; }
public float Acceleration { get; set; } = 0.25f;
public float MaxSpeed { get; set; } = 6f;
#endregion
#endregion
#region SetDefaults
public override void SetStaticDefaults()
{
@@ -178,14 +185,14 @@ namespace CalamityMod.NPCs.SunkenSea
{
base.SetDefaults();
// BannerItem = ItemType<SharkoonBanner>();
NPC.damage = 20;
NPC.lifeMax = 350;
NPC.defense = 5;
NPC.knockBackResist = 0.15f;
NPC.chaseable = false;
NPC.aiStyle = -1;
AIType = -1;
NPC.width = 52;
NPC.height = 46;
NPC.noGravity = true;
@@ -193,8 +200,6 @@ namespace CalamityMod.NPCs.SunkenSea
NPC.HitSound = SoundID.NPCHit1;
NPC.DeathSound = SoundID.NPCDeath1;
NPC.value = Item.buyPrice(0, 0, 5, 0);
// Banner = NPC.type;
// BannerItem = ModContent.ItemType<SharkoonBanner>();
NPC.Calamity().VulnerableToHeat = false;
NPC.Calamity().VulnerableToSickness = true;
@@ -202,109 +207,41 @@ namespace CalamityMod.NPCs.SunkenSea
NPC.Calamity().VulnerableToWater = false;
}
public override void HitEffect(NPC.HitInfo hit)
{
for (int k = 0; k < 5; k++)
{
Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.RedMoss, hit.HitDirection, -1f, 0, default, 1f);
}
if (NPC.life <= 0)
{
for (int k = 0; k < 25; k++)
{
Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.RedMoss, hit.HitDirection, -1f, 0, default, 1f);
}
}
}
public override bool CanBeHitByNPC(NPC attacker)
{
if (attacker.whoAmI == NPC.whoAmI)
return false;
return true;
}
public override void OnHitByNPC(NPC attacker)
{
if (IsBig)
CurrentBehavior = ExplodingBehavior;
}
public override void OnHitByItem(Player player, Item item, NPC.HitInfo hit, int damageDone)
{
if (IsBig)
CurrentBehavior = ExplodingBehavior;
}
public override void OnHitByProjectile(Projectile projectile, NPC.HitInfo hit, int damageDone)
{
if (IsBig)
CurrentBehavior = ExplodingBehavior;
}
#endregion
#region AI
#region Behavior
protected override void BehaviorOnSpawn()
protected override bool PlayerSearchFilter(Player p)
{
return base.PlayerSearchFilter(p) || p == CurrentPlayer && Vector2.DistanceSquared(NPC.Center, p.Center) < 960f * 960f;
}
protected override bool NPCSearchFilter(NPC n)
{
return base.NPCSearchFilter(n) || (n == CurrentPrey || n == CurrentPredator) && Vector2.DistanceSquared(NPC.Center, n.Center) < 960f * 960f;
}
public override void OnSpawn(IEntitySource source)
{
CurrentBehavior = IdlingBehavior;
WeightedRandom<PersonalityType> randomPersonality = new();
randomPersonality.Add(PersonalityType.Shy, 0.4f);
randomPersonality.Add(PersonalityType.Curious, 0.4f);
randomPersonality.Add(PersonalityType.Paranoid, 0.2f);
Personality = randomPersonality.Get();
DetectionDistance = 320f;
ConeDetectionAngle = MathHelper.ToRadians(30f);
if (Personality == PersonalityType.Curious)
{
DetectionDistance *= 1.5f;
ConeDetectionAngle *= 1.5f;
RandomIdleMovementUnlikeliness /= 2;
}
if (Personality == PersonalityType.Paranoid)
MaximumSpeed *= 1.5f;
NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt();
NPC.GravityMultiplier *= 2f;
NPC.MaxFallSpeedMultiplier *= 2f;
}
protected override void CreatureAI()
public override void AI()
{
CurrentBehavior?.Invoke();
// Sets the direction at which it looks at the cone.
// This makes it look at the direction it's going.
if (!NPC.velocity.HasNaNs())
ConeDetectionDirection = (NPC.rotation * MathF.Sign(NPC.velocity.Y) + (NPC.spriteDirection == -1 ? MathHelper.Pi : 0f)).ToRotationVector2();
// Leans the Sharkoon towards the direction it's going.
NPC.rotation = MathHelper.ToRadians(NPC.velocity.Length() * 3f) * MathF.Sign(NPC.velocity.X);
// When the Sharkoon is fast enough in one direction, it'll turn to that direction.
if (MathF.Abs(NPC.velocity.X) > 1f)
NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X);
// When the Sharkoon's paranoid, it'll explode at anything that isn't prey which gets close to the Sharkoon.
bool isEntityPlayerOrNonPreyNPC = NearestEntity is not null && (NearestEntity is Player || NearestEntity is NPC npc && !HuntNPCs.Contains(npc.type));
if (isEntityPlayerOrNonPreyNPC)
{
bool isWithinDistance = NPC.DistanceSQ(NearestEntity.Center) < DistanceToKaboom * DistanceToKaboom;
if (IsBig && Personality == PersonalityType.Paranoid && isEntityPlayerOrNonPreyNPC && isWithinDistance)
CurrentBehavior = ExplodingBehavior;
}
NPC.rotation = MathHelper.ToRadians(NPC.velocity.X * 3f);
NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X);
// When it has already exploded, a timer will start, which when finished it'll make the Sharkoon recover.
if (!IsBig)
if (!CanExplode)
{
RecoverTimer++;
if (RecoverTimer > TimeToRecover)
if (RecoverTimer > ExplosionCooldown)
CurrentBehavior = RecoveringBehavior;
}
@@ -312,92 +249,29 @@ namespace CalamityMod.NPCs.SunkenSea
if (!NPC.wet && !IsExploding)
CurrentBehavior = OutsideWaterBehavior;
// Clamps the velocity at all times.
if (NPC.velocity.LengthSquared() > MaximumSpeed * MaximumSpeed)
NPC.velocity = NPC.velocity.SafeNormalize(Vector2.UnitY) * MaximumSpeed;
if (ScaleSquish.Y > 1f)
// Reset any squish that is done to the Sharkoon.
if (_scaleSquish.Y > 1f)
{
ScaleSquish.Y -= 0.025f;
if (ScaleSquish.Y < 1f)
ScaleSquish.Y = 1f;
}
}
protected override void OnBehaviorChange(Action newBehavior)
{
// Obviously, when it gets to the exploding behaivor, it should make the explosion animation.
if (newBehavior == ExplodingBehavior)
Animation = AnimationState.Explosion;
// Resets the timer when it needs to use it again.
if (newBehavior == RecoveringBehavior || CurrentBehavior == RecoveringBehavior)
RecoverTimer = 0f;
// When it gets outside of water, it'll try to gravitate downards towards the water.
if (newBehavior == OutsideWaterBehavior)
NPC.noGravity = false;
}
protected override void OnPreyDetection(NPC prey)
{
// If it's not a small fish and it's not being chased by a predator, the Sharkoon may hunt.
if (IsBig && CurrentPredator is null && !IsExploding)
{
CurrentBehavior = HuntBehavior;
ScaleSquish.Y += 0.4f;
React(Color.Orange * 0.6f, EmoteExpressionParticle.EmoteType.Exclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f });
}
}
protected override void OnPredatorDetection(NPC predator)
{
// If it detects a predator, time to run.
if (!IsExploding)
{
CurrentBehavior = AvoidBehavior;
React(Color.Red * 0.6f, EmoteExpressionParticle.EmoteType.DoubleExclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f });
ScaleSquish.Y += 0.4f;
}
}
protected override void OnPlayerDetection(Player player)
{
// When there's a predator, player's shouldn't matter.
if (CurrentPredator is not null)
return;
// If the Sharkoon is shy, it'll run away from the player.
if (Personality == PersonalityType.Shy)
{
CurrentBehavior = AvoidBehavior;
React(Color.Orange, EmoteExpressionParticle.EmoteType.QuestionExclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f });
ScaleSquish.Y += 0.4f;
}
if (Personality == PersonalityType.Curious)
{
React(Color.Green, EmoteExpressionParticle.EmoteType.Question, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f });
ScaleSquish.Y += 0.4f;
_scaleSquish.Y -= 0.025f;
if (_scaleSquish.Y < 1f)
_scaleSquish.Y = 1f;
}
}
private void IdlingBehavior()
{
if (_pathfindingTask.Result != null)
// At random, the mob will choose a random nearby point and pathfind there.
PathfindingTask task = null;
if (Main.rand.NextBool(IdleRandomMovementUnlikeliness))
{
// While it hasn't decided yet which path to follow, it'll deaccelerate and stand still.
NPC.velocity *= 0.95f;
// Randomly, it'll decide a path whose destination is somewhere around him.
if (Main.rand.NextBool(RandomIdleMovementUnlikeliness) && !_pathfindingTask.IsCompleted)
_pathfindingTask = CalamityUtils.FindPathAsync(new(NPC.Center, Main.rand.NextVector2Circular(400f, 400f), SunkenSeaTileValidity));
_randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(IdleMinPathDistance, IdleMaxPathDistance);
NPC.netUpdate = true;
task = new PathfindingTask(NPC.Center, _randomPathPoint, SunkenSeaTileValidity);
}
else
GenericPathFollowing(Acceleration);
this.DoPathfinding(task);
}
private void HuntBehavior()
private void HuntingBehavior()
{
// If there's no more prey, go back to idling.
if (CurrentPrey is null)
@@ -406,72 +280,49 @@ namespace CalamityMod.NPCs.SunkenSea
return;
}
if (!HasLineOfSight(CurrentPrey.Center))
{
if (_pathfindingTask.Result != null)
PathfindingPoints = _pathfindingTask.Result;
if (_pathfindingTask.Result != null)
GenericPathFollowing(Acceleration);
else
_pathfindingTask = CalamityUtils.FindPathAsync(new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity));
}
// With sight, just go straight at him. Without it, try to pathfind over them.
if (!NPC.HasSight(CurrentPrey.Center))
this.DoPathfinding(new PathfindingTask(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity));
else
{
NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration;
if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed;
}
}
private void AvoidBehavior()
private void FleeingBehavior()
{
// Depending on the personality, the Sharkoon will choose who to avoid.
Entity entityToAvoid = null;
switch (Personality)
{
case PersonalityType.Shy:
entityToAvoid = (NearestEntity is NPC nearestNPC && HuntNPCs.Contains(nearestNPC.type)) ? null : NearestEntity;
break;
case PersonalityType.Curious:
case PersonalityType.Paranoid:
entityToAvoid = CurrentPredator;
break;
}
// Check who is the avoided entity specifically.
_avoidedEntity = _avoidedEntity is NPC ? CurrentPredator : CurrentPlayer;
// If there aren't any more targets detected, go back to idling.
if (entityToAvoid is null)
// If the avoided entity is gone, go back to idling.
if (_avoidedEntity == null)
{
CurrentBehavior = IdlingBehavior;
return;
}
// When it's going in a direction and it detects that it'll stumble into tiles, it'll try to path-find a way to continue avoiding whichever entity.
const int TileAnticipationDistance = 5 * 16;
const float AngleVariance = 2.2f; // In radians.
const int MaxAttemptsToFindPath = 20;
const int MinimumEscapeDistance = 160;
const int MaximumEscapeDistance = 320;
if (Main.tile[(NPC.Center + NPC.DirectionFrom(entityToAvoid.Center) * TileAnticipationDistance).ToTileCoordinates()].IsTileSolid() && !HasPath)
// While it doesn't have any obstacles in front of it, run away in a straight line.
// Try to manuever if there are any obstacles.
if (!Main.tile[(NPC.Center + NPC.DirectionFrom(_avoidedEntity.Center) * FleeTileAnticipationDistance).ToTileCoordinates()].IsTileSolid())
{
Vector2 randomEscapePoint;
int attempts = 0;
do
{
randomEscapePoint = NPC.Center + NPC.DirectionFrom(entityToAvoid.Center).RotatedByRandom(AngleVariance) * Main.rand.NextFloat(MinimumEscapeDistance, MaximumEscapeDistance);
attempts++;
}
while (Main.tile[randomEscapePoint.ToTileCoordinates()].IsTileSolid() || attempts < MaxAttemptsToFindPath);
NPC.velocity += NPC.DirectionFrom(_avoidedEntity.Center) * Acceleration;
_pathfindingTask = CalamityUtils.FindPathAsync(new(NPC.Center, randomEscapePoint, SunkenSeaTileValidity));
// Cap the speed if MaxSpeed has been surpassed.
if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed)
NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed;
}
else
{
float distanceFromAvoided = Vector2.Distance(NPC.Center, _avoidedEntity.Center);
_randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f);
NPC.netUpdate = true;
this.DoPathfinding(new PathfindingTask(NPC.Center, _randomPathPoint, SunkenSeaTileValidity));
}
if (_pathfindingTask.Result != null)
PathfindingPoints = _pathfindingTask.Result;
if (HasPath)
GenericPathFollowing(Acceleration);
else
NPC.velocity += NPC.DirectionFrom(entityToAvoid.Center) * Acceleration;
// If it's capable of exploding and the predator's within distance, kaboom.
if (IsBig && NPC.DistanceSQ(entityToAvoid.Center) < DistanceToKaboom * DistanceToKaboom && entityToAvoid is NPC predator && AvoidNPCs.Contains(predator.type))
if (CanExplode && NPC.DistanceSQ(_avoidedEntity.Center) < ExplosionDistance * ExplosionDistance && _avoidedEntity is NPC predator && PredatorIDs.Contains(predator.type))
CurrentBehavior = ExplodingBehavior;
}
@@ -491,16 +342,16 @@ namespace CalamityMod.NPCs.SunkenSea
if (NPC.frame.Y >= NPC.height * 16)
{
Animation = AnimationState.Shrunk;
CurrentBehavior = PreviousBehavior;
CurrentBehavior = _previousBehavior;
}
}
private void RecoveringBehavior()
{
if (RecoverTimer >= TimeRecovering)
if (RecoverTimer >= RecoveringTime)
{
Animation = AnimationState.Normal;
CurrentBehavior = PreviousBehavior;
CurrentBehavior = _previousBehavior;
}
// Deaccelerates to stay still.
@@ -510,12 +361,10 @@ namespace CalamityMod.NPCs.SunkenSea
// a dedicated server doesn't need to load these.
if (!Main.dedServ)
{
float fade = Utils.GetLerpValue(TimeRecovering, 0, RecoverTimer);
float rotFactor = 360f;
float fade = Utils.GetLerpValue(RecoveringTime, 0, RecoverTimer);
if (Main.rand.NextBool())
{
float rot = MathHelper.ToRadians(rotFactor);
Vector2 velOffset = CalamityUtils.RandomVelocity(50f, 20f, 70f, 0.04f);
Vector2 velOffset = RandomVelocity(50f, 20f, 70f, 0.04f);
velOffset *= Main.rand.NextFloat(15, 20) * fade;
Dust dust = Dust.NewDustPerfect(NPC.Center + velOffset * 2.5f, 267, -velOffset * Main.rand.NextFloat(0.08f, 0.12f) * 1.5f, 0, default, Main.rand.NextFloat(0.8f, 0.95f));
dust.noGravity = true;
@@ -531,10 +380,94 @@ namespace CalamityMod.NPCs.SunkenSea
if (NPC.wet)
{
NPC.noGravity = true;
CurrentBehavior = PreviousBehavior;
CurrentBehavior = _previousBehavior;
}
}
private void OnBehaviorChange(Action newBehavior)
{
// Obviously, when it gets to the exploding behaivor, it should make the explosion animation.
if (newBehavior == ExplodingBehavior)
Animation = AnimationState.Explosion;
// Resets the timer when it needs to use it again.
if (newBehavior == RecoveringBehavior || CurrentBehavior == RecoveringBehavior)
RecoverTimer = 0f;
// When it gets outside of water, it'll try to gravitate downards towards the water.
if (newBehavior == OutsideWaterBehavior)
NPC.noGravity = false;
Path = null;
}
protected override void OnPreyDetection(NPC prey)
{
// If it's not a small fish and it's not being chased by a predator, the Sharkoon may hunt.
if (CanExplode && CurrentPredator is null && !IsExploding)
{
CurrentBehavior = HuntingBehavior;
_scaleSquish.Y += 0.4f;
}
}
protected override void OnPredatorDetection(NPC predator)
{
// If it detects a predator, time to run.
if (!IsExploding)
{
CurrentBehavior = FleeingBehavior;
_avoidedEntity = predator;
_scaleSquish.Y += 0.4f;
}
}
protected override void OnPlayerDetection(Player player)
{
// When there's a predator, player's shouldn't matter.
if (CurrentPredator is not null && !IsExploding)
return;
CurrentBehavior = FleeingBehavior;
_avoidedEntity = player;
_scaleSquish.Y += 0.4f;
}
public override void HitEffect(NPC.HitInfo hit)
{
for (int k = 0; k < 5; k++)
{
Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.RedMoss, hit.HitDirection, -1f, 0, default, 1f);
}
if (NPC.life <= 0)
{
for (int k = 0; k < 25; k++)
{
Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.RedMoss, hit.HitDirection, -1f, 0, default, 1f);
}
}
}
public override bool CanBeHitByNPC(NPC attacker) => attacker.type != Type;
public override void OnHitByNPC(NPC attacker)
{
if (CanExplode)
CurrentBehavior = ExplodingBehavior;
}
public override void OnHitByItem(Player player, Item item, NPC.HitInfo hit, int damageDone)
{
if (CanExplode)
CurrentBehavior = ExplodingBehavior;
}
public override void OnHitByProjectile(Projectile projectile, NPC.HitInfo hit, int damageDone)
{
if (CanExplode)
CurrentBehavior = ExplodingBehavior;
}
private void Kaboom()
{
if (Main.netMode != NetmodeID.MultiplayerClient)
@@ -544,11 +477,13 @@ namespace CalamityMod.NPCs.SunkenSea
NPC.Center,
Vector2.Zero,
ProjectileType<SharkoonExplosion>(),
NPC.damage,
NPC.damage * 10,
10f,
Main.myPlayer);
ai0: NPC.whoAmI);
}
AddScreenshakeAt(NPC.Center, 15f);
// VFX and sound effects go here,
// a dedicated server doesn't need to load these.
if (!Main.dedServ)
@@ -574,8 +509,6 @@ namespace CalamityMod.NPCs.SunkenSea
SoundStyle boom = new("CalamityMod/Sounds/Custom/SharkoonBoom");
SoundEngine.PlaySound(boom with { Volume = 0.7f, PitchVariance = 0.15f }, NPC.Center);
}
NetUpdate();
}
#endregion
@@ -587,21 +520,21 @@ namespace CalamityMod.NPCs.SunkenSea
/// </summary>
private void ChangeAnimation(int animationFrames, int timePerAnimationFrame, bool loops)
{
AnimationFrames = animationFrames;
TimePerAnimationFrame = timePerAnimationFrame;
AnimationLoop = loops;
_animationFrames = animationFrames;
_timePerAnimationFrame = timePerAnimationFrame;
_animationLoop = loops;
}
public override void FindFrame(int frameHeight)
{
NPC.frameCounter++;
if (NPC.frameCounter > TimePerAnimationFrame)
if (NPC.frameCounter > _timePerAnimationFrame)
{
NPC.frame.Y += frameHeight;
NPC.frame.Y = Math.Min(NPC.frame.Y, AnimationFrames * frameHeight);
NPC.frame.Y = Math.Min(NPC.frame.Y, _animationFrames * frameHeight);
NPC.frameCounter = 0;
if (AnimationLoop)
NPC.frame.Y = NPC.frame.Y % (AnimationFrames * frameHeight);
if (_animationLoop)
NPC.frame.Y = NPC.frame.Y % (_animationFrames * frameHeight);
}
}
@@ -613,36 +546,25 @@ namespace CalamityMod.NPCs.SunkenSea
Vector2 anchorPoint = frame.Size() * 0.5f;
SpriteEffects flip = NPC.spriteDirection == -1 ? SpriteEffects.FlipHorizontally : SpriteEffects.None;
if (Personality == PersonalityType.Paranoid)
drawPosition += Main.rand.NextVector2Circular(1.5f, 1.5f);
spriteBatch.Draw(texture, drawPosition, frame, NPC.GetAlpha(drawColor), NPC.rotation, anchorPoint, ScaleSquish, flip, 0f);
spriteBatch.Draw(texture, drawPosition, frame, NPC.GetAlpha(drawColor), NPC.rotation, anchorPoint, _scaleSquish, flip, 0f);
return false;
}
#endregion
#region Syncing
#region Sycning
private Vector2 _randomPathPoint;
public override void SendExtraAI(BinaryWriter writer)
{
base.SendExtraAI(writer);
writer.Write7BitEncodedInt(AnimationFrames);
writer.Write7BitEncodedInt(TimePerAnimationFrame);
writer.Write(AnimationLoop);
writer.Write(MaximumSpeed);
writer.Write7BitEncodedInt(RandomIdleMovementUnlikeliness);
writer.WriteVector2(_randomPathPoint);
}
public override void ReceiveExtraAI(BinaryReader reader)
{
base.ReceiveExtraAI(reader);
AnimationFrames = reader.Read7BitEncodedInt();
TimePerAnimationFrame = reader.Read7BitEncodedInt();
AnimationLoop = reader.ReadBoolean();
MaximumSpeed = reader.ReadSingle();
RandomIdleMovementUnlikeliness = reader.Read7BitEncodedInt();
_randomPathPoint = reader.ReadVector2();
}
#endregion
+65 -344
View File
@@ -1,13 +1,10 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CalamityMod.Enums;
using CalamityMod.Particles;
using CalamityMod.Systems.Collections;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.Audio;
using Terraria.GameContent.Bestiary;
using Terraria.ID;
using Terraria.ModLoader;
@@ -16,182 +13,71 @@ using static Terraria.Utilities.NPCUtils;
namespace CalamityMod.NPCs.SunkenSea
{
/// <summary>
/// An abstract class that gives an NPC the memebers needed to be a Sunken Sea NPC.<br/>
/// These have the ability to hunt both players and NPCs, and also have a list of NPCs they hunt and avoid.
/// An abstract class that provides the necessary members for an NPC to function as a Sunken Sea NPC.<br/>
/// These NPCs can hunt both players and other NPCs, and maintain lists of NPCs they hunt and avoid.
/// </summary>
public abstract class SunkenSeaNPC : ModNPC
{
#region Fields & Properties
private NPC _currentPrey;
private NPC _currentPredator;
private Player _currentPlayer;
/// <summary>
/// Since a lot of these NPCs change behaviors a lot, this abstract class provides an <see cref="Action"/> property to store and trigger behaviors.<br/>
/// Automatically resets <see cref="PathfindingPoints"/> and <see cref="PathTimer"/> to not cause errors.
/// A list of NPC IDs that this creature hunts.
/// </summary>
protected Action CurrentBehavior
{
get => _currentBehavior;
set
{
OnBehaviorChange(value);
PathfindingPoints = null;
PathPointIndex = 0;
PreviousBehavior = _currentBehavior;
_currentBehavior = value;
NetUpdate();
}
}
private Action _currentBehavior;
protected abstract List<int> PreyIDs { get; }
/// <summary>
/// The previous behavior that was used for <see cref="CurrentBehavior"/>.
/// A list of NPC IDs that this creature avoids.
/// </summary>
protected Action PreviousBehavior { get; private set; }
protected abstract List<int> PredatorIDs { get; }
/// <summary>
/// A lot of these Sunken Sea creatures use the <see cref="CalamityUtils.AStar"/> pathfinding algorithm,<br/>
/// so this abstract class provides a <see cref="List{T}"/> so you can store the paths.<br/>
/// Defaults to <see langword="null"/>.
/// The biome flags that define where this Sunken Sea NPC can spawn.
/// </summary>
protected List<Vector2> PathfindingPoints { get; set; }
protected abstract SunkenSeaBiomeFlags BiomeDesignation { get; }
/// <summary>
/// The probablity that this Sunken Sea NPC spawns given the conditions.
/// </summary>
protected abstract float SpawningChance { get; }
protected int PathPointIndex { get; set; }
private bool _hasSpawned;
#region Targetting
/// <summary>
/// A list which stores the NPC's IDs that this creature hunts.
/// </summary>
protected abstract List<int> HuntNPCs { get; }
/// <summary>
/// A list which stores the NPC's IDs that this creature avoids.
/// </summary>
protected abstract List<int> AvoidNPCs { get; }
/// <summary>
/// The current NPC that this creature has detected as prey.
/// The current NPC that this creature has identified as prey.
/// </summary>
protected NPC CurrentPrey
{
get => _currentPrey;
private set
{
if (value != _currentPrey && value != null)
if (value != null && (_currentPrey == null || _currentPrey.whoAmI != value.whoAmI))
OnPreyDetection(value);
_currentPrey = value;
}
}
private NPC _currentPrey;
/// <summary>
/// The current NPC that this creature has detected as a predator.
/// The current NPC that this creature has identified as a predator.
/// </summary>
protected NPC CurrentPredator
{
get => _currentPredator;
private set
{
if (value != _currentPredator && value != null)
if (value != null && (_currentPredator == null || _currentPredator.whoAmI != value.whoAmI))
OnPredatorDetection(value);
_currentPredator = value;
}
}
private NPC _currentPredator;
/// <summary>
/// The current Player that this creature has detected.
/// The current player that this creature has detected.
/// </summary>
protected Player CurrentPlayer
{
get => _currentPlayer;
private set
{
if (value != _currentPlayer && value != null)
if (value != null && (_currentPlayer == null || _currentPlayer.whoAmI != value.whoAmI))
OnPlayerDetection(value);
_currentPlayer = value;
}
}
private Player _currentPlayer;
/// <summary>
/// The nearest entity detected, could be an NPC or Player.
/// </summary>
protected Entity NearestEntity { get; private set; }
/// <summary>
/// The distance detection radius.<br/>
/// Defaults to 300 pixels.
/// </summary>
protected float DetectionDistance { get; set; } = 300f;
/// <summary>
/// The direction of the cone used to detect targets.<br/>
/// Defaults to <see cref="Vector2.UnitX"/> times the direction.<br/>
/// When set, it normalizes the vector.
/// </summary>
protected Vector2 ConeDetectionDirection
{
get => _coneDetectionDirection;
set
{
_coneDetectionDirection = value.SafeNormalize(Vector2.UnitX * NPC.direction);
NetUpdate();
}
}
private Vector2 _coneDetectionDirection;
/// <summary>
/// How open the cone detection is -- given an angle.<br/>
/// Defaults to 45 degrees.
/// </summary>
protected float ConeDetectionAngle { get; set; } = MathHelper.ToRadians(45f);
/// <summary>
/// When a this creature has lost sight of a target, it'll still have a sense of permanence.<br/>
/// This means that, even if it can't see it, it can know it's there.<br/>
/// This property states how much seconds it can know it's there.<br/>
/// Defaults to 3 seconds.
/// </summary>
protected virtual float PermanenceSenseTime => CalamityUtils.SecondsToFrames(3f);
private int _permanenceSenseTimer;
/// <summary>
/// Whether or not the creature has detected anything at all.
/// </summary>
protected bool HasAnyTargets => CurrentPrey != null || CurrentPredator != null || CurrentPlayer != null;
#endregion
#region Biome Designation
/// <summary>
/// The biomes that this Sunken Sea NPC belongs to.
/// </summary>
protected abstract SunkenSeaBiomeFlags BiomeDesignation { get; }
/// <summary>
/// The spawn conditions for each biome that this Sunken Sea NPC belongs to.
/// </summary>
protected List<Func<NPCSpawnInfo, bool>> BiomeSpawnConditions { get; private set; } = [];
#endregion
#endregion
#region ModNPC Overrides
public override void SetStaticDefaults()
{
@@ -201,273 +87,108 @@ namespace CalamityMod.NPCs.SunkenSea
public override void SetDefaults()
{
List<int> biomeTypes = [];
foreach (var flag in Enum.GetValues<SunkenSeaBiomeFlags>())
{
if (flag == SunkenSeaBiomeFlags.None)
continue;
NPC.aiStyle = -1;
AIType = -1;
if (!BiomeDesignation.HasFlag(flag))
continue;
SpawnModBiomes = Enum.GetValues<SunkenSeaBiomeFlags>()
.Where(flag => flag != SunkenSeaBiomeFlags.None &&
flag != SunkenSeaBiomeFlags.UndergroundDesert &&
BiomeDesignation.HasFlag(flag))
.Select(flag => SunkenSeaBiomeCorrespondentDict.Dict[flag].BiomeType)
.ToArray();
if (!SunkenSeaBiomeCorrespondentDict.TryGet(flag, out var spawnCondition, out var biomeType))
continue;
// Apply Conditions and Biome Types
BiomeSpawnConditions.Add(spawnCondition);
if (flag != SunkenSeaBiomeFlags.UndergroundDesert)
biomeTypes.Add(biomeType);
}
SpawnModBiomes = [.. biomeTypes];
Banner = Type;
}
public override void SetBestiary(BestiaryDatabase database, BestiaryEntry bestiaryEntry) => bestiaryEntry.Info.AddRange([new FlavorTextBestiaryInfoElement($"Mods.CalamityMod.Bestiary.{Name}")]);
public override void SetBestiary(BestiaryDatabase database, BestiaryEntry bestiaryEntry)
=> bestiaryEntry.Info.AddRange([new FlavorTextBestiaryInfoElement($"Mods.CalamityMod.Bestiary.{Name}")]);
public override float SpawnChance(NPCSpawnInfo spawnInfo)
public override bool PreAI()
{
if (BiomeSpawnConditions.Any(f => f.Invoke(spawnInfo)) && spawnInfo.Water && !spawnInfo.Player.Calamity().clamity)
return SpawningChance;
return 0f;
}
public sealed override void AI()
{
if (!_hasSpawned)
{
_coneDetectionDirection = Vector2.UnitX * NPC.direction;
BehaviorOnSpawn();
_hasSpawned = true;
NetUpdate();
}
UpdateTargets();
CreatureAI();
return true;
}
#endregion
#region Methods
/// <summary>
/// Same function as OnSpawn, but this one actually syncs to the server.
/// Called when this NPC is hit by another NPC. Override this method to define custom behavior when attacked.
/// </summary>
protected virtual void BehaviorOnSpawn() { }
/// <summary>
/// A method that is called on <see cref="AI"/> every frame, to put your actual enemy AI.
/// </summary>
protected virtual void CreatureAI() { }
/// <summary>
/// A method that is triggered when this NPC's behavior is changed.
/// </summary>
protected virtual void OnBehaviorChange(Action newBehavior) { }
/// <summary>
/// A custom method for when this NPC is hit by another NPC.
/// </summary>
/// <param name="attacker"></param>
/// <param name="attacker">The NPC that attacked this creature.</param>
public virtual void OnHitByNPC(NPC attacker) { }
/// <summary>
/// A method that is triggered when this creature has detected a prey.
/// Called when this creature detects a prey NPC. Override this method to define custom behavior upon detecting prey.
/// </summary>
/// <param name="prey">The NPC that has been detected as prey.</param>
protected virtual void OnPreyDetection(NPC prey) { }
/// <summary>
/// A method that is triggered when this creature has detected a predator.
/// Called when this creature detects a predator NPC. Override this method to define custom behavior upon detecting a predator.
/// </summary>
/// <param name="predator">The NPC that has been detected as a predator.</param>
protected virtual void OnPredatorDetection(NPC predator) { }
/// <summary>
/// A method that is triggered when this creature detects a player.
/// Called when this creature detects a player. Override this method to define custom behavior upon detecting a player.
/// </summary>
/// <param name="player">The player that has been detected.</param>
protected virtual void OnPlayerDetection(Player player) { }
/// <summary>
/// Whether or not a detected player is valid to be set as a target given some conditions.
/// Determines whether a detected player is a valid target based on specific conditions.
/// </summary>
protected virtual bool PlayerSearchFilter(Player p)
{
if (!HasLineOfSight(p.Center))
return false;
bool isInsideCone = Vector2.Dot(_coneDetectionDirection, NPC.DirectionTo(p.Center)) >= MathF.Cos(ConeDetectionAngle) && NPC.DistanceSQ(p.Center) < DetectionDistance * DetectionDistance;
bool isInsideCirlceWhenAware = HasAnyTargets && NPC.DistanceSQ(p.Center) <= DetectionDistance * DetectionDistance;
if (isInsideCone || isInsideCirlceWhenAware)
return true;
return false;
}
/// <param name="p">The player to evaluate.</param>
/// <returns><see langword="true"/> if the NPC is a valid target; otherwise, <see langword="false"/>.</returns>
protected virtual bool PlayerSearchFilter(Player p) => NPC.HasSight(p.Center) && Vector2.DistanceSquared(NPC.Center, p.Center) < 72900f;
/// <summary>
/// Whether or not a detected NPC is valid to be set as a target given some conditions.
/// Determines whether a detected NPC is a valid target based on specific conditions.
/// </summary>
protected virtual bool NPCSearchFilter(NPC n)
{
if (!HasLineOfSight(n.Center))
return false;
bool isInsideCone = Vector2.Dot(_coneDetectionDirection, NPC.DirectionTo(n.Center)) >= MathF.Cos(ConeDetectionAngle) && NPC.DistanceSQ(n.Center) < DetectionDistance * DetectionDistance;
bool isInsideCirlceWhenAware = HasAnyTargets && NPC.DistanceSQ(n.Center) <= DetectionDistance * DetectionDistance;
if (isInsideCone || isInsideCirlceWhenAware)
return true;
return false;
}
/// <param name="n">The NPC to evaluate.</param>
/// <returns><see langword="true"/> if the NPC is a valid target; otherwise, <see langword="false"/>.</returns>
protected virtual bool NPCSearchFilter(NPC n) => NPC.HasSight(n.Center) && Vector2.DistanceSquared(NPC.Center, n.Center) < 72900f;
/// <summary>
/// A method that finds and updates the current detected targets of this creature.
/// Updates the current targets of this creature, including prey, predators, and players, based on detection logic.
/// </summary>
protected void UpdateTargets()
{
var searchResults = SearchForTarget(NPC, playerFilter: PlayerSearchFilter, npcFilter: NPCSearchFilter);
if (searchResults.FoundTarget)
{
CurrentPlayer = searchResults.NearestTankOwner;
NearestEntity = searchResults.NearestTankOwner;
if (searchResults.FoundNPC)
{
if (AvoidNPCs.Contains(searchResults.NearestNPC.type))
if (PredatorIDs.Contains(searchResults.NearestNPC.type))
CurrentPredator = searchResults.NearestNPC;
else
CurrentPredator = null;
else if (HuntNPCs.Contains(searchResults.NearestNPC.type))
if (PreyIDs.Contains(searchResults.NearestNPC.type))
CurrentPrey = searchResults.NearestNPC;
if (searchResults.NearestNPCDistance < searchResults.NearestTankDistance)
NearestEntity = searchResults.NearestNPC;
else
CurrentPrey = null;
}
NetUpdate();
CurrentPlayer = searchResults.NearestTankOwner;
}
else
{
_permanenceSenseTimer++;
if (_permanenceSenseTimer > PermanenceSenseTime)
{
CurrentPlayer = null;
NearestEntity = null;
CurrentPredator = null;
CurrentPrey = null;
_permanenceSenseTimer = 0;
}
}
}
#endregion
#region Helper Methods
protected bool HasPath => PathfindingPoints is not null;
protected bool SunkenSeaTileValidity(Point point) =>
Main.tile[point].LiquidAmount > 125 && Main.tile[point].LiquidType == LiquidID.Water && NPC.DoesEntityFitInPath(point, 6, 6);
/// <summary>
/// A quickhand method to follow a path found.
/// </summary>
protected void GenericPathFollowing(float acceleration)
{
Vector2 currentlyFollowedPathPoint = PathfindingPoints[PathPointIndex];
NPC.velocity += NPC.DirectionTo(currentlyFollowedPathPoint) * acceleration;
if (NPC.DistanceSQ(currentlyFollowedPathPoint) < 48f * 48f)
{
PathPointIndex++;
PathPointIndex = (int)MathHelper.Clamp(PathPointIndex, 0, PathfindingPoints.Count - 1);
}
if (PathPointIndex == PathfindingPoints.Count - 1)
{
PathPointIndex = 0;
PathfindingPoints = null;
CurrentPredator = null;
CurrentPrey = null;
CurrentPlayer = null;
}
}
/// <summary>
/// A quick method to check whether this NPC has line of sight with something.
/// Checks whether a specific tile is valid for this NPC, considering water level and entity size.
/// </summary>
protected bool HasLineOfSight(Vector2 position) => Collision.CanHitLine(NPC.Center, 0, 0, position, 0, 0);
/// <summary>
/// Spawns an emote particle.
/// </summary>
protected void React(Color emoteColor, EmoteExpressionParticle.EmoteType emoteImage, SoundStyle? sound = null)
/// <param name="point">The tile location to check.</param>
/// <returns><see langword="true"/> if the tile is valid; otherwise, <see langword="false"/>.</returns>
protected bool SunkenSeaTileValidity(Point point)
{
if (!Main.dedServ)
{
var emoteDirection = -Vector2.UnitY.RotatedByRandom(MathHelper.PiOver4) * Main.rand.NextFloat(2f, 3f);
Particle emote = new EmoteExpressionParticle(
NPC.Center + emoteDirection * 2f,
emoteDirection,
2.2f,
emoteColor,
Main.rand.Next(30, 46),
emoteImage);
GeneralParticleHandler.SpawnParticle(emote);
if (sound is not null)
SoundEngine.PlaySound(sound, NPC.Center);
}
Point actualFuckingPoint = new Point(point.X * 16, point.Y * 16);
return NPC.Hitbox.Contains(actualFuckingPoint)
|| !NPC.GetIntersectingHitboxPoints(
actualFuckingPoint, 10, 10).Any(a => Main.tile[a].IsTileSolid() || Main.tile[a].LiquidAmount < 255 || Main.tile[a].LiquidType != LiquidID.Water);
}
#endregion
#region Syncing
/// <summary>
/// A quick method to both do <see cref="NPC.netUpdate"/> and set <see cref="NPC.netSpam"/>.<br/>
/// Defaults <see cref="NPC.netSpam"/> to 0.
/// </summary>
protected void NetUpdate(int netSpam = 0)
{
NPC.netUpdate = true;
NPC.netSpam = netSpam;
}
public override void SendExtraAI(BinaryWriter writer)
{
writer.Write7BitEncodedInt(CurrentPrey.whoAmI);
writer.Write7BitEncodedInt(CurrentPredator.whoAmI);
writer.Write7BitEncodedInt(CurrentPlayer.whoAmI);
writer.Write7BitEncodedInt(NearestEntity.whoAmI);
writer.Write(DetectionDistance);
writer.WritePackedVector2(_coneDetectionDirection);
writer.Write(ConeDetectionAngle);
writer.Write7BitEncodedInt(_permanenceSenseTimer);
writer.Write7BitEncodedInt(PathfindingPoints.Count);
foreach (var point in PathfindingPoints)
writer.WritePackedVector2(point);
writer.Write7BitEncodedInt(PathPointIndex);
writer.Write(_hasSpawned);
}
public override void ReceiveExtraAI(BinaryReader reader)
{
CurrentPrey.whoAmI = reader.Read7BitEncodedInt();
CurrentPredator.whoAmI = reader.Read7BitEncodedInt();
CurrentPlayer.whoAmI = reader.Read7BitEncodedInt();
NearestEntity.whoAmI = reader.Read7BitEncodedInt();
DetectionDistance = reader.ReadSingle();
_coneDetectionDirection = reader.ReadPackedVector2();
ConeDetectionAngle = reader.ReadSingle();
_permanenceSenseTimer = reader.Read7BitEncodedInt();
int count = reader.Read7BitEncodedInt();
for (int i = 0; i < count; i++)
PathfindingPoints.Add(reader.ReadPackedVector2());
PathPointIndex = reader.Read7BitEncodedInt();
_hasSpawned = reader.ReadBoolean();
}
#endregion
}
}
+3 -1
View File
@@ -1,5 +1,6 @@
using CalamityMod.NPCs.SunkenSea;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.ModLoader;
namespace CalamityMod.Projectiles.Enemy
@@ -13,12 +14,13 @@ namespace CalamityMod.Projectiles.Enemy
public override void SetDefaults()
{
Projectile.hostile = true;
Projectile.friendly = true;
Projectile.width = Projectile.height = Sharkoon.ExplosionRadius * 2;
Projectile.timeLeft = 2;
}
public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox)
=> CalamityUtils.CircularHitboxCollision(Projectile.Center, Sharkoon.ExplosionRadius, targetHitbox);
public override bool? CanHitNPC(NPC target) => target.whoAmI != Projectile.ai[0];
}
}
+1 -1
View File
@@ -72,7 +72,7 @@ namespace CalamityMod.Projectiles.Magic
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone)
{
target.AddBuff(ModContent.BuffType<CrushDepth>(), 240);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 240);
if (Projectile.numHits == 0)
Projectile.velocity *= 0.4f;
}
@@ -256,7 +256,7 @@ namespace CalamityMod.Projectiles.Melee
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone)
{
target.AddBuff(ModContent.BuffType<CrushDepth>(), 300);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 300);
if (spinMode2 && Projectile.numHits == 0)
{
@@ -81,7 +81,7 @@ namespace CalamityMod.Projectiles.Melee
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone)
{
target.AddBuff(ModContent.BuffType<CrushDepth>(), 240);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 240);
}
}
}
+2 -2
View File
@@ -61,9 +61,9 @@ namespace CalamityMod.Projectiles.Ranged
}
}
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType<CrushDepth>(), 180);
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 180);
public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(ModContent.BuffType<CrushDepth>(), 180);
public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 180);
public override bool PreDraw(ref Color lightColor)
{
+2 -2
View File
@@ -72,7 +72,7 @@ namespace CalamityMod.Projectiles.Rogue
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone)
{
target.AddBuff(ModContent.BuffType<CrushDepth>(), 240);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 240);
SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position);
@@ -112,7 +112,7 @@ namespace CalamityMod.Projectiles.Rogue
public override void OnHitPlayer(Player target, Player.HurtInfo info)
{
target.AddBuff(ModContent.BuffType<CrushDepth>(), 240);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 240);
SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position);
+2 -2
View File
@@ -79,7 +79,7 @@ namespace CalamityMod.Projectiles.Rogue
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone)
{
target.AddBuff(ModContent.BuffType<CrushDepth>(), 180);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 180);
SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position);
@@ -119,7 +119,7 @@ namespace CalamityMod.Projectiles.Rogue
public override void OnHitPlayer(Player target, Player.HurtInfo info)
{
target.AddBuff(ModContent.BuffType<CrushDepth>(), 180);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 180);
SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position);
+2 -2
View File
@@ -71,7 +71,7 @@ namespace CalamityMod.Projectiles.Rogue
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone)
{
target.AddBuff(ModContent.BuffType<CrushDepth>(), 120);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 120);
SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position);
@@ -105,7 +105,7 @@ namespace CalamityMod.Projectiles.Rogue
public override void OnHitPlayer(Player target, Player.HurtInfo info)
{
target.AddBuff(ModContent.BuffType<CrushDepth>(), 120);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 120);
SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position);
+2 -2
View File
@@ -57,12 +57,12 @@ namespace CalamityMod.Projectiles.Rogue
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone)
{
target.AddBuff(ModContent.BuffType<CrushDepth>(), 120);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 120);
}
public override void OnHitPlayer(Player target, Player.HurtInfo info)
{
target.AddBuff(ModContent.BuffType<CrushDepth>(), 120);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 120);
}
}
}
+2 -2
View File
@@ -64,7 +64,7 @@ namespace CalamityMod.Projectiles.Rogue
target.AddBuff(ModContent.BuffType<ArmorCrunch>(), 120);
if (Projectile.Calamity().stealthStrike)
{
target.AddBuff(ModContent.BuffType<CrushDepth>(), 120);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 120);
Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero, ModContent.ProjectileType<JawsShockwave>(), Projectile.damage, 10f, Projectile.owner, 0, 0);
}
}
@@ -76,8 +76,8 @@ namespace CalamityMod.Projectiles.Rogue
target.AddBuff(ModContent.BuffType<ArmorCrunch>(), 120);
if (Projectile.Calamity().stealthStrike)
{
target.AddBuff(ModContent.BuffType<CrushDepth>(), 120);
Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero, ModContent.ProjectileType<JawsShockwave>(), Projectile.damage, 10f, Projectile.owner, 0, 0);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 120);
}
}
+2 -2
View File
@@ -58,9 +58,9 @@ namespace CalamityMod.Projectiles.Rogue
}
}
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType<CrushDepth>(), 240);
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 240);
public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(ModContent.BuffType<CrushDepth>(), 240);
public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 240);
public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) => CalamityUtils.CircularHitboxCollision(Projectile.Center, 160f, targetHitbox);
}
+2 -2
View File
@@ -121,13 +121,13 @@ namespace CalamityMod.Projectiles.Rogue
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone)
{
target.AddBuff(ModContent.BuffType<CrushDepth>(), 180);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 180);
OnHitEffects();
}
public override void OnHitPlayer(Player target, Player.HurtInfo info)
{
target.AddBuff(ModContent.BuffType<CrushDepth>(), 180);
target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 180);
OnHitEffects();
}
+4 -1
View File
@@ -1,4 +1,5 @@
using CalamityMod.Buffs.Summon;
using CalamityMod.Buffs.DamageOverTime;
using CalamityMod.Buffs.Summon;
using CalamityMod.Items.Weapons.Summon;
using CalamityMod.Projectiles.BaseProjectiles;
using Microsoft.Xna.Framework;
@@ -211,6 +212,8 @@ namespace CalamityMod.Projectiles.Summon
// The minion will only have contact damage if it's on latching mode.
public override bool MinionContactDamage() => State == AIState.Latching;
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 240);
// The minion will do 1.5x damage if it's latched on.
public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) => modifiers.SourceDamage *= CalamarisLament.LatchingDamageMultiplier;
@@ -1,4 +1,5 @@
using CalamityMod.Items.Weapons.Summon;
using CalamityMod.Buffs.DamageOverTime;
using CalamityMod.Items.Weapons.Summon;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
@@ -72,6 +73,8 @@ namespace CalamityMod.Projectiles.Summon
// and hit DoG's head and/or tail reliably and without penetration.
public override bool? CanDamage() => Projectile.getRect().Intersects(TargetShot.getRect()) ? null : false;
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType<HadopelagicPressure>(), 120);
public override void OnKill(int timeLeft)
{
for (int i = 0; i < 15; i++)
+2
View File
@@ -893,6 +893,8 @@ namespace CalamityMod
return false;
}
public static bool HasSight(this NPC npc, Vector2 target) => Collision.CanHit(npc.Center, 1, 1, target, 1, 1);
#region Boss Spawning
/// <summary>
/// Shortcut for the generic boss summon message.
+348 -151
View File
@@ -1,13 +1,316 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using CalamityMod.Projectiles.Typeless;
using Microsoft.Xna.Framework;
using Terraria;
using static CalamityMod.CalamityUtils;
namespace CalamityMod
{
/// <summary>
/// Represents an entity that is capable of finding and following a complex path.<br/>
/// To use this interface, supply all of the required properties, and then simply call <c>this.DoPathfinding()</c> in your entity's movement logic.
/// </summary>
public interface IPathFinder
{
/// <summary>
/// Represents the working task for calculating this entity's complex path.<br/>
/// <br/>
/// If you want to manually access the result of this task, make sure to check <see cref="PathfindingTask.Ready"/> before accessing the value of <see cref="PathfindingTask.Result"/>.<br/>
/// <br/>
/// Accessing <see cref="PathfindingTask.Result"/> before execution has completed will result in the calling thread being blocked until execution is complete.
/// </summary>
public PathfindingTask Path { get; set; }
/// <summary>
/// The current position of this entity. Only used to calculate movement for this entity, not pathfinding.<br/>
/// In most cases, this should look like the following, where <c>ENTITY</c> is replace by your entity instance.
/// <code>public Vector2 Position { get => ENTITY.center; }</code>
/// </summary>
public Vector2 Position { get; }
/// <summary>
/// The current velocity of this entity. Only used to calculate movement for this entity, not pathfinding.<br/>
/// In most cases, this should look like the following, where <c>ENTITY</c> is replace by your entity instance.
/// <code>public Vector2 Velocity { get => ENTITY.velocity; }</code>
/// </summary>
public Vector2 Velocity { get; set; }
/// <summary>
/// The acceleration this entity should use when moving. Only used to calculate movement for this entity, not pathfinding.
/// </summary>
public float Acceleration { get; }
/// <summary>
/// The maximum speed this entity should be able to reach while moving. Only used to calculate movement for this entity, not pathfinding.
/// </summary>
public float MaxSpeed { get; }
/// <summary>
/// Defines how this entity should move to the next point. Contains a default implementation with basic acceleration towards the next point.<br/>
/// This method should return <see langword="true"/> when the entity has reached its target point, and <see langword="false"/> otherwise.<br/>
/// <br/>
/// The target point is specified by <paramref name="nextPoint"/> - usually index 0 in the <see cref="Paths"/> task result.
/// </summary>
/// <param name="nextPoint"></param>
/// <returns></returns>
public bool FollowPath(Vector2 nextPoint)
{
// Accelerate to the target point.
Velocity += (nextPoint - Position).SafeNormalize(Vector2.Zero) * Acceleration;
// Cap the speed if MaxSpeed has been surpassed.
if (Velocity.LengthSquared() > MaxSpeed * MaxSpeed)
Velocity = Velocity.SafeNormalize(Vector2.UnitY) * MaxSpeed;
// If the entity is within 48 pixels of its target point, consider the point reached.
if (Vector2.DistanceSquared(Position, nextPoint) < 48f * 48f)
return true;
// Otherwise, continue following.
return false;
}
/// <summary>
/// Defines how this entity should behave while there is no current path to follow.<br/>
/// By default, decelerates and stops based on <see cref="Acceleration"/>.
/// </summary>
public void IdleBehavior() => Velocity *= 0.95f;
/// <summary>
/// Assigns the value of <see cref="Paths"/> to <paramref name="pathfindingTask"/> and executes the pathfinding calculations on a background thread.<br/>
/// You can override this to do your own modifications to the pathfinding task before assigning and starting the calculations.
/// </summary>
public void FindPath(PathfindingTask pathfindingTask)
{
if (pathfindingTask == null)
return;
Path = pathfindingTask;
Path.Run();
}
}
/// <summary>
/// Represents a task for calculating a complex path.<br/>
/// Allows for synchronous access to an asynchronous execution state, while still providing blocking access where needed.
/// </summary>
public class PathfindingTask(
Vector2 start,
Vector2 end,
Func<Point, bool> tileValidity = null,
Func<Point, Point, float> distanceFunction = null,
Func<Point, Point, float> heuristic = null)
{
public PathfindingTask(Vector2 start, Vector2 end) : this(start, end, null, null, null)
{ }
/// <summary>
/// The result of this pathfinding task.
/// </summary>
public List<Vector2> Result { get => _task.Task.Result; }
/// <summary>
/// Whether this pathfinding task has completed running.
/// </summary>
public bool Ready { get; private set; } = false;
/// <summary>
/// Whether this pathfinding task is still currently running.
/// </summary>
public bool Running { get; private set; } = false;
/// <summary>
/// The starting position of this pathfinding task.
/// </summary>
public Vector2 StartPosition { get; init; } = start;
/// <summary>
/// The ending position of this pathfinding task.
/// </summary>
public Vector2 EndPosition { get; init; } = end;
// Interal task representation of the work.
private readonly TaskCompletionSource<List<Vector2>> _task = new();
// Internal containing object for the actual work.
private readonly PathfindingWork _work = new(start, end, tileValidity, distanceFunction, heuristic);
/// <summary>
/// Begins execution of this pathfinding task on a background thread.
/// </summary>
public void Run()
{
Running = true;
ThreadPool.QueueUserWorkItem((pathfindingTask) =>
{
var task = pathfindingTask as PathfindingTask;
task._task.TrySetResult(task._work.CalculatePath());
task.Ready = true;
task.Running = false;
},
this);
}
}
public static partial class CalamityUtils
{
/// <summary>
/// Causes this <see cref="IPathFinder"/> to perform path finding and follow the path result, idling when a path is not available.<br/>
/// This method should be called every frame that you want your entity to follow it's pathfinding logic.
/// </summary>
public static void DoPathfinding(this IPathFinder pathfinder, Vector2 target) => pathfinder.DoPathfinding(new PathfindingTask(pathfinder.Position, target));
/// <summary>
/// Causes this <see cref="IPathFinder"/> to perform path finding and follow the path result, idling when a path is not available.<br/>
/// This method should be called every frame that you want your entity to follow it's pathfinding logic.
/// </summary>
public static void DoPathfinding(this IPathFinder pathfinder, PathfindingTask task, bool continuouslyUpdatePath = false)
{
// If the task has been started but is not finished yet, just idle.
if (pathfinder.Path?.Running ?? false)
pathfinder.IdleBehavior();
// If the task has not been started,
// or was previously unable to find a path,
// OR is now being told to follow a new path...
//
// start the task (potentially again).
else if (pathfinder.Path == null || // Not started
pathfinder.Path.Result == null || // Unable to find previous path
pathfinder.Path.Result.Count == 0 || // Previous path is done being followed
(continuouslyUpdatePath && pathfinder.Path.EndPosition != task.EndPosition)) // New path
{
pathfinder.FindPath(task);
pathfinder.IdleBehavior();
}
// Otherwise, the task has been started, completed, and found a valid path.
// Follow the found path.
else
{
// Follows the point at index 0 of the path result.
Vector2 nextPoint = pathfinder.Path.Result[0];
// Once that point is reached, it is removed from the list of points to follow.
if (pathfinder.FollowPath(nextPoint))
pathfinder.Path.Result.RemoveAt(0);
}
}
/// <summary>
/// Represents the working computation for a <see cref="PathfindingTask"/>.
/// </summary>
/// <remarks>
/// <para>
/// Has 2 overloads, one for inputting the start and end nodes as <see cref="Vector2"/>, and the other one as <see cref="Point"/>.
/// </para>
/// <para>
/// This record contains the start and end nodes, along with functions for tile validity, distance calculation, and heuristic estimation.
/// </para>
/// <para>
/// - <see cref="TileValidity"/>: A function that checks if a tile at a given point is valid for traversal. If not provided, all non-solid tiles are considered valid.<br/>
/// - <see cref="DistanceFunction"/>: A function that calculates the distance between two points. Defaults to <see cref="OctileDistance"/>.<br/>
/// - <see cref="Heuristic"/>: A function that estimates the cost from a given point to the end point. Defaults to <see cref="OctileDistance"/>.<br/>
/// </para>
/// </remarks>
public record PathfindingWork(Node Start, Node End, Func<Point, bool> TileValidity, Func<Point, Point, float> DistanceFunction, Func<Point, Point, float> Heuristic)
{
private static readonly Func<Point, bool> DefaultTileValidity = point => true;
private static readonly Func<Point, Point, float> DefaultDistanceFunction = OctileDistance;
private static readonly Func<Point, Point, float> DefaultHeuristic = OctileDistance;
public PathfindingWork(
Point start,
Point end,
Func<Point, bool> tileValidity = null,
Func<Point, Point, float> distanceFunction = null,
Func<Point, Point, float> heuristic = null) : this(
new Node(start),
new Node(end),
tileValidity ?? DefaultTileValidity,
distanceFunction ?? DefaultDistanceFunction,
heuristic ?? DefaultHeuristic
)
{
}
public PathfindingWork(
Vector2 start,
Vector2 end,
Func<Point, bool> tileValidity = null,
Func<Point, Point, float> distanceFunction = null,
Func<Point, Point, float> heuristic = null) : this(
new Node(start.ToTileCoordinates()),
new Node(end.ToTileCoordinates()),
tileValidity ?? DefaultTileValidity,
distanceFunction ?? DefaultDistanceFunction,
heuristic ?? DefaultHeuristic
)
{
}
/// <summary>
/// Calculates a path from the start to the end position using the A* pathfinding algorithm.
/// </summary>
///
/// <returns>
/// A list of <see cref="Vector2"/> positions representing the path from start to end, or <see langword="null"/> if no path is found.
/// </returns>
public List<Vector2> CalculatePath()
{
if (Main.tile[End.Position].IsTileSolid())
return null;
var openSet = new List<Node>();
var closedSet = new HashSet<Node>();
openSet.Add(Start);
while (openSet.Count > 0)
{
// Get the node with the lowest F value.
var current = openSet[0];
for (int i = 1; i < openSet.Count; i++)
{
if (openSet[i].F < current.F || (openSet[i].F == current.F && openSet[i].H < current.H))
current = openSet[i];
}
openSet.Remove(current);
closedSet.Add(current);
// Check if we've reached the goal.
if (current.Position == End.Position)
return current.ReconstructPath();
// Generate neighbors.
foreach (var neighbor in current.GetNeighbors())
{
if (closedSet.Contains(neighbor) || Main.tile[neighbor.Position].IsTileSolid() || !TileValidity.Invoke(neighbor.Position))
continue;
float tentativeG = current.G + DistanceFunction.Invoke(current.Position, neighbor.Position);
if (!openSet.Contains(neighbor) || tentativeG < neighbor.G)
{
neighbor.Parent = current;
neighbor.G = tentativeG;
neighbor.H = Heuristic.Invoke(neighbor.Position, End.Position);
if (!openSet.Contains(neighbor))
openSet.Add(neighbor);
}
}
}
return null; // No path found.
}
}
/// <summary>
/// Represents a node in a pathfinding algorithm, containing position, cost, and parent information.
/// </summary>
@@ -27,169 +330,42 @@ namespace CalamityMod
}
public override int GetHashCode() => Position.GetHashCode();
}
/// <summary>
/// Represents the parameters required for the <see cref="FindPathAsync(PathfindingParams)"/> method.
/// </summary>
/// <remarks>
/// <para>
/// Has 2 overloads, one for inputting the start and end nodes as <see cref="Vector2"/>, and the other one as <see cref="Point"/>.
/// </para>
/// <para>
/// This record contains the start and end nodes, along with functions for tile validity, distance calculation, and heuristic estimation.
/// </para>
/// <para>
/// - <see cref="TileValidity"/>: A function that checks if a tile at a given point is valid for traversal. If not provided, all non-solid tiles are considered valid.<br/>
/// - <see cref="DistanceFunction"/>: A function that calculates the distance between two points. Defaults to <see cref="OctileDistance"/>.<br/>
/// - <see cref="Heuristic"/>: A function that estimates the cost from a given point to the end point. Defaults to <see cref="OctileDistance"/>.<br/>
/// </para>
/// </remarks>
public record PathfindingParams(Node Start, Node End, Func<Point, bool> TileValidity, Func<Point, Point, float> DistanceFunction, Func<Point, Point, float> Heuristic)
{
private static readonly Func<Point, bool> DefaultTileValidity = point => true;
private static readonly Func<Point, Point, float> DefaultDistanceFunction = OctileDistance;
private static readonly Func<Point, Point, float> DefaultHeuristic = OctileDistance;
public PathfindingParams(
Point start,
Point end,
Func<Point, bool> tileValidity = null,
Func<Point, Point, float> distanceFunction = null,
Func<Point, Point, float> heuristic = null) : this(
new Node(start),
new Node(end),
tileValidity ?? DefaultTileValidity,
distanceFunction ?? DefaultDistanceFunction,
heuristic ?? DefaultHeuristic
)
public List<Node> GetNeighbors()
{
}
var neighbors = new List<Node>(Directions.Count);
public PathfindingParams(
Vector2 start,
Vector2 end,
Func<Point, bool> tileValidity = null,
Func<Point, Point, float> distanceFunction = null,
Func<Point, Point, float> heuristic = null) : this(
new Node(start.ToTileCoordinates()),
new Node(end.ToTileCoordinates()),
tileValidity ?? DefaultTileValidity,
distanceFunction ?? DefaultDistanceFunction,
heuristic ?? DefaultHeuristic
)
{
}
}
int nodeX = Position.X;
int nodeY = Position.Y;
/// <summary>
/// Asynchronously finds a path from the start to the end position using the A* pathfinding algorithm.
/// </summary>
///
/// <param name="parameters">The parameters for the pathfinding algorithm, including start, end, and cost functions.</param>
///
/// <returns>
/// A task that represents the asynchronous operation.<br/> The task result contains a list of <see cref="Vector2"/> positions
/// representing the path from start to end, or <see langword="null"/> if no path is found.
/// </returns>
///
/// <remarks>
/// <para>
/// This method runs the pathfinding calculations on a separate CPU thread using <see cref="Task.Run"/>.<br/>
/// Use <see cref="Task.IsCompleted"/> to check if the pathfinding is complete, and <see cref="Task{TResult}.Result"/>
/// to retrieve the resulting path.
/// </para>
/// </remarks>
///
/// <example>
/// <code>
/// var parameters = new PathfindingParams(start, end, TileValidity, DistanceFunction, Heuristic);
/// var pathTask = FindPathAsync(parameters);
/// if (pathTask.Result != null)
/// PathPoints = pathTask.Result;
/// </code>
/// </example>
public static async Task<List<Vector2>> FindPathAsync(PathfindingParams parameters)
{
return await Task.Run(() =>
{
var openSet = new List<Node>();
var closedSet = new HashSet<Node>();
openSet.Add(parameters.Start);
while (openSet.Count > 0)
foreach (var direction in Directions)
{
// Get the node with the lowest F value.
var current = openSet[0];
for (int i = 1; i < openSet.Count; i++)
{
if (openSet[i].F < current.F || (openSet[i].F == current.F && openSet[i].H < current.H))
current = openSet[i];
}
int newX = nodeX + (int)direction.X;
int newY = nodeY + (int)direction.Y;
openSet.Remove(current);
closedSet.Add(current);
// Check if we've reached the goal.
if (current.Position == parameters.End.Position)
return ReconstructPath(current);
// Generate neighbors.
foreach (var neighbor in GetNeighbors(current))
{
if (closedSet.Contains(neighbor) || Main.tile[neighbor.Position].IsTileSolid() || !parameters.TileValidity.Invoke(neighbor.Position))
continue;
float tentativeG = current.G + parameters.DistanceFunction.Invoke(current.Position, neighbor.Position);
if (!openSet.Contains(neighbor) || tentativeG < neighbor.G)
{
neighbor.Parent = current;
neighbor.G = tentativeG;
neighbor.H = parameters.Heuristic.Invoke(neighbor.Position, parameters.End.Position);
if (!openSet.Contains(neighbor))
openSet.Add(neighbor);
}
}
if (WorldGen.InWorld(newX, newY))
neighbors.Add(new Node(new Point(newX, newY)));
}
return null; // No path found.
});
}
private static List<Node> GetNeighbors(Node node)
{
var neighbors = new List<Node>(Directions.Count);
int nodeX = node.Position.X;
int nodeY = node.Position.Y;
foreach (var direction in Directions)
{
int newX = nodeX + (int)direction.X;
int newY = nodeY + (int)direction.Y;
if (WorldGen.InWorld(newX, newY))
neighbors.Add(new Node(new Point(newX, newY)));
return neighbors;
}
return neighbors;
}
private static List<Vector2> ReconstructPath(Node node)
{
var pathStack = new Stack<Vector2>();
while (node != null)
public List<Vector2> ReconstructPath()
{
pathStack.Push(node.Position.ToWorldCoordinates());
node = node.Parent;
var pathStack = new Stack<Vector2>();
var node = this;
while (node != null)
{
pathStack.Push(node.Position.ToWorldCoordinates());
node = node.Parent;
}
var path = new List<Vector2>(pathStack.Count);
path.AddRange(pathStack);
return path;
}
var path = new List<Vector2>(pathStack.Count);
path.AddRange(pathStack);
return path;
}
#region Heuristic Functions
@@ -239,5 +415,26 @@ namespace CalamityMod
return doesFit;
}
public static List<Point> GetIntersectingHitboxPoints(this Entity entity, Point position, int fluffX = 0, int fluffY = 0)
{
Rectangle hitbox = entity.Hitbox;
hitbox.Location = new Point(position.X - hitbox.Width / 2, position.Y - hitbox.Height / 2);
hitbox.Inflate(fluffX, fluffY);
int startX = (int)MathF.Floor(hitbox.Left / 16);
int endX = (int)Math.Floor((hitbox.Right - float.Epsilon) / 16);
int startY = (int)MathF.Floor(hitbox.Top / 16);
int endY = (int)Math.Floor((hitbox.Bottom - float.Epsilon) / 16);
List<Point> intersectingPoints = [];
for (int i = startX; i <= endX; i++)
{
for (int j = startY; j <= endY; j++)
intersectingPoints.Add(new Point(i, j));
}
return intersectingPoints;
}
}
}