diff --git a/NPCs/SunkenSea/Sharkoon.cs b/NPCs/SunkenSea/Sharkoon.cs index f624cbbcf8..a21b583ac7 100644 --- a/NPCs/SunkenSea/Sharkoon.cs +++ b/NPCs/SunkenSea/Sharkoon.cs @@ -9,66 +9,54 @@ using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.Audio; using Terraria.GameContent; -using Terraria.GameContent.Bestiary; using Terraria.ID; using Terraria.ModLoader; using Terraria.ModLoader.Utilities; -using static CalamityMod.CalamityUtils; +using Terraria.Utilities; +using static Terraria.ModLoader.ModContent; namespace CalamityMod.NPCs.SunkenSea { - public class Sharkoon : ModNPC + public class Sharkoon : SunkenSeaNPC { - public static float TargetDistanceDetection = 160f; - public static int IdleMovementUnlikeliness = 250; - public static float MaxIdleSpeed = 3f; - public static float IdleMovementMaxRange = 800f; + public static float DistanceToKaboom = 80f; + public static float IdleMovementMaxRange = 640f; public static int ExplosionRadius = 80; public static float TimeToRecover = 600f; public static float TimeRecovering = 120f; #region Fields & Properties - /// - /// The that this has detected as its target. - /// - private Player PlayerTarget + protected override List HuntNPCs => new() { - get => playerTarget; - set - { - playerTarget = value; - NetUpdate(); - } - } - private Player playerTarget; + NPCType(), + NPCType(), + NPCType(), + NPCType(), + }; + + protected override List AvoidNPCs => new() + { + // NPCType(), + // NPCType(), + NPCType(), + // NPCType, + }; /// - /// The different AI states this enemy can have. + /// The different types of personality this NPC can have. /// - private enum AIState { OutsideWater, Normal, Exploding, Recovering } + private enum PersonalityType { Shy, Curious, Paranoid } /// - /// The current AI state of this enemy. + /// The current personality of this NPC. /// - private AIState State + private PersonalityType Personality { - get => (AIState)NPC.ai[0]; + get => (PersonalityType)NPC.ai[0]; set { NPC.ai[0] = (float)value; - - if (value == AIState.Exploding) - Animation = AnimationState.Explosion; - - // When outside of water, it'll gravitate down, can't swim. - NPC.noGravity = value != AIState.OutsideWater; - - // We remove that taken path when it changes state, - // unless it just came out of the water accidentally. - if (value != AIState.OutsideWater) - PathPositions = null; - NetUpdate(); } } @@ -133,33 +121,36 @@ namespace CalamityMod.NPCs.SunkenSea private bool AnimationLoop = true; /// - /// A netcode-synced boolean that is when this is the first frame that it exists,
- /// meaning it just spawned. + /// A timer used to know when the NPC should recover after it explodes. ///
- private bool HasSpawned - { - get => NPC.ai[2] == 1f; - set - { - NPC.ai[2] = value.ToInt(); - NetUpdate(); - } - } - - private ref float PathTimer => ref NPC.ai[3]; - - private ref float RecoverTimer => ref NPC.Calamity().newAI[0]; + private ref float RecoverTimer => ref NPC.ai[2]; /// - /// A list of which makes a path for the to follow. + /// The maximum speed this NPC can have, it cannot be faster than this number. /// - private List PathPositions; + private float MaximumSpeed = 4f; + + /// + /// How unlikely is the Sharkoon going to move normally.
+ /// Defaults to 250. + ///
+ private int RandomIdleMovementUnlikeliness = 250; + + /// + /// Whether or not the Sharkoon is capable of exploding. + /// + private bool IsBig => Animation == AnimationState.Normal; + + /// + /// The squish of this NPC while drawing. + /// + private Vector2 ScaleSquish = Vector2.One; #endregion #region Other Overridden Methods - public override void SetStaticDefaults() => Main.npcFrameCount[Type] = 16; + protected override void ExtraSetStaticDefaults() => Main.npcFrameCount[Type] = 16; public override void SetDefaults() { @@ -189,14 +180,6 @@ namespace CalamityMod.NPCs.SunkenSea NPC.Calamity().VulnerableToWater = false; } - public override void SetBestiary(BestiaryDatabase database, BestiaryEntry bestiaryEntry) - { - bestiaryEntry.Info.AddRange(new IBestiaryInfoElement[] - { - new FlavorTextBestiaryInfoElement("Mods.CalamityMod.Bestiary.Sharkoon") - }); - } - public override float SpawnChance(NPCSpawnInfo spawnInfo) { if (spawnInfo.Player.Calamity().ZoneSunkenSea && spawnInfo.Water && !spawnInfo.Player.Calamity().clamity) @@ -221,129 +204,211 @@ namespace CalamityMod.NPCs.SunkenSea } } - public override bool CanHitPlayer(Player target, ref int cooldownSlot) => false; + public override bool CanBeHitByNPC(NPC attacker) + { + if (attacker.whoAmI == NPC.whoAmI) + return false; + + return true; + } + + public override void OnHitByProjectile(Projectile projectile, NPC.HitInfo hit, int damageDone) => CurrentBehavior = ExplodingBehavior; #endregion #region AI - public override void AI() + protected override void CreatureOnSpawn() { - if (!HasSpawned) + CurrentBehavior = IdlingBehavior; + + WeightedRandom 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) { - NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt(); - NPC.GravityMultiplier *= 2f; - NPC.MaxFallSpeedMultiplier *= 2f; - HasSpawned = true; + DetectionDistance *= 1.5f; + ConeDetectionAngle *= 1.5f; + RandomIdleMovementUnlikeliness /= 2; } - switch (State) - { - case AIState.OutsideWater: - OutsideWaterState(); - return; - case AIState.Normal: - NormalState(); - break; - case AIState.Exploding: - ExplodingState(); - break; - case AIState.Recovering: - RecoveringState(); - break; - } + if (Personality == PersonalityType.Paranoid) + MaximumSpeed *= 1.5f; + + NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt(); + NPC.GravityMultiplier *= 2f; + NPC.MaxFallSpeedMultiplier *= 2f; } - /// - /// The behavior of this NPC when it's outside of water. - /// - private void OutsideWaterState() + protected override void CreatureAI() { - if (NPC.wet) - { - State = AIState.Normal; - return; - } - } + CurrentBehavior?.Invoke(); - /// - /// The behavior of this NPC when it it's just doing normal behavior. - /// - private void NormalState() - { - // If the NPC's outside of water, switch the state. - if (!NPC.wet) + 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.LengthSquared()) * MathF.Sign(NPC.velocity.X); + + if (MathF.Abs(NPC.velocity.X) > 2f) + NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); + + bool isEntityPlayerOrNonPreyNPC = NearestEntity is not null && (NearestEntity is Player || NearestEntity is NPC && !HuntNPCs.Contains((NearestEntity as NPC).type)); + if (isEntityPlayerOrNonPreyNPC) { - State = AIState.OutsideWater; - return; + bool isWithinDistance = NPC.DistanceSQ(NearestEntity.Center) < DistanceToKaboom * DistanceToKaboom; + if (IsBig && Personality == PersonalityType.Paranoid && isEntityPlayerOrNonPreyNPC && isWithinDistance) + CurrentBehavior = ExplodingBehavior; } - // If the NPC finds a valid target and it still is normal, go, commit boom. - if (Animation == AnimationState.Normal && FindsTarget()) - { - State = AIState.Exploding; - return; - } - - if (Animation == AnimationState.Shrunk) + if (!IsBig) { RecoverTimer++; - if (RecoverTimer >= TimeToRecover) - { - RecoverTimer = 0f; - State = AIState.Recovering; - return; - } + if (RecoverTimer > TimeToRecover) + CurrentBehavior = RecoveringBehavior; } - if (PathPositions == null) - { - // When there's no path, it'll deacclerate and eventually stay still. - NPC.velocity *= 0.95f; + if (!NPC.wet) + CurrentBehavior = OutsideWaterBehavior; - // At a random moment, it'll choose to move. - if (Main.rand.NextBool(IdleMovementUnlikeliness)) - { - var grid = GetPathGrid(); - PathPositions = AStar.GetPath(grid, NPC.Center.ToSafeTileCoordinates(), grid[Main.rand.Next(grid.Count)]); - PathTimer = 0f; - NetUpdate(); - } - } + if (NPC.velocity.LengthSquared() > MaximumSpeed * MaximumSpeed) + NPC.velocity = NPC.velocity.SafeNormalize(Vector2.UnitY) * MaximumSpeed; - else - { - // Iterates through all the vectors in the path as time goes on. - Vector2 followedPathPoint = PathPositions[(int)Math.Floor(PathTimer)]; + if (ScaleSquish.Y > 1f) + ScaleSquish.Y -= 0.025f; - // Accelerates towards the followed point. - NPC.velocity += NPC.Center.DirectionTo(followedPathPoint) * 0.03f; - - PathTimer += 0.07f; - PathTimer = MathF.Min(PathTimer, PathPositions.Count - 1); - - // If very near the end point or too far from the followed path, reset the path. - if (NPC.Center.DistanceSQ(PathPositions[^1]) < 14400f || NPC.Center.DistanceSQ(followedPathPoint) > 102400f) - { - PathPositions = null; - NetUpdate(); - } - } - - NPC.velocity = Vector2.Clamp(NPC.velocity, -Vector2.One * MaxIdleSpeed, Vector2.One * MaxIdleSpeed); - NPC.rotation = MathHelper.ToRadians(NPC.velocity.Length() * 3f) * MathF.Sign(NPC.velocity.X); - NPC.spriteDirection = -MathF.Sign(NPC.velocity.X); + if (ScaleSquish.Y < 1f) + ScaleSquish.Y = 1f; } - /// - /// The behavior of this NPC when it is currently trying to explode. - /// - private void ExplodingState() + protected override void OnBehaviorChange(Action newBehavior) + { + if (newBehavior == ExplodingBehavior) + Animation = AnimationState.Explosion; + + if (newBehavior == RecoveringBehavior) + RecoverTimer = 0f; + + if (PreviousBehavior == RecoveringBehavior) + RecoverTimer = 0f; + + if (newBehavior == HuntBehavior || newBehavior == AvoidBehavior) + ScaleSquish.Y += 0.4f; + + 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 Sharkoon may hunt. + if (IsBig && CurrentPredator is null) + CurrentBehavior = HuntBehavior; + } + + protected override void OnPredatorDetection(NPC predator) + { + // Regardless of anything, if it detects a predator, time to run. + CurrentBehavior = AvoidBehavior; + } + + protected override void OnPlayerDetection(Player player) + { + // If the Sharkoon is shy, it'll run away from the player. + if (Personality == PersonalityType.Shy) + CurrentBehavior = AvoidBehavior; + } + + private void IdlingBehavior() + { + if (PathfindingPoints is null) + { + // 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)) + MakePath(NPC.Center + Main.rand.NextVector2CircularEdge(IdleMovementMaxRange, IdleMovementMaxRange) * Main.rand.NextFloat(0.75f, 1f), IdleMovementMaxRange); + } + else + GenericPathFollowing(acceleration: 0.07f, pathFollowingSpeed: 0.07f, conditionToFinishFollowing: FinishedPathfinding()); + } + + private void HuntBehavior() + { + // If there's no more prey, go back to idling. + if (CurrentPrey is null) + { + CurrentBehavior = IdlingBehavior; + return; + } + + if (!HasLineOfSight(CurrentPrey.Center)) + { + if (PathfindingPoints is not null) + GenericPathFollowing(acceleration: 0.14f, pathFollowingSpeed: 0.1f, conditionToFinishFollowing: FinishedPathfinding()); + else + MakePath(CurrentPrey.Center, CalamityUtils.ManhattanDistance(NPC.Center, CurrentPrey.Center)); + } + else + NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * 0.14f; + } + + private void AvoidBehavior() + { + // Depending on the personality, the Sharkoon will choose who to avoid. + Entity entityToAvoid = null; + switch (Personality) + { + case PersonalityType.Shy: + entityToAvoid = (NearestEntity is NPC && HuntNPCs.Contains((NearestEntity as NPC).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 = IdlingBehavior; + return; + } + + if (PathfindingPoints is null) + { + Point randomEscapePoint = (NPC.Center + NPC.DirectionFrom(entityToAvoid.Center).RotatedByRandom(MathHelper.PiOver2) * Main.rand.NextFloat(300f, 400f)).ToSafeTileCoordinates(); + + var grid = CalamityUtils.AStar.MakeGenericGrid(NPC.Center, 300f); + + while (!grid.Contains(randomEscapePoint)) + { + randomEscapePoint = (NPC.Center + NPC.DirectionFrom(entityToAvoid.Center).RotatedByRandom(MathHelper.PiOver2) * Main.rand.NextFloat(300f, 400f)).ToSafeTileCoordinates(); + } + + MakePath(randomEscapePoint.ToWorldCoordinates(), grid); + } + else + GenericPathFollowing(acceleration: 0.14f, pathFollowingSpeed: 0.07f, conditionToFinishFollowing: FinishedPathfinding()); + + // If it's capable of exploding and the predator's within distance, kaboom. + if (IsBig && NPC.DistanceSQ(entityToAvoid.Center) < DistanceToKaboom * DistanceToKaboom && entityToAvoid is NPC && AvoidNPCs.Contains((entityToAvoid as NPC).type)) + CurrentBehavior = ExplodingBehavior; + } + + private void ExplodingBehavior() { // Deaccelerate. NPC.velocity *= 0.95f; - if (Animation != AnimationState.Shrunk) + if (IsBig) Lighting.AddLight(NPC.Center, Color.Orange.ToVector3() * Utils.GetLerpValue(NPC.height, NPC.height * 9, NPC.frame.Y, true)); // On the exact frame that the NPC explodes, it'll will, indeed, explode. @@ -354,39 +419,40 @@ namespace CalamityMod.NPCs.SunkenSea if (NPC.frame.Y >= NPC.height * 16) { Animation = AnimationState.Shrunk; - State = AIState.Normal; + CurrentBehavior = PreviousBehavior; } } - /// - /// The behavior of this NPC when it is recovering its ability to kaboom. - /// - private void RecoveringState() + private void RecoveringBehavior() { if (RecoverTimer >= TimeRecovering) { Animation = AnimationState.Normal; - RecoverTimer = 0f; - State = AIState.Normal; - return; + CurrentBehavior = PreviousBehavior; } // Deaccelerates to stay still. NPC.velocity *= 0.95f; - + // VFX and sound effects go here, // a dedicated server doesn't need to load these. if (!Main.dedServ) { // HI XYK! } - + RecoverTimer++; } - /// - /// What happens when this NPC explodes. - /// + private void OutsideWaterBehavior() + { + if (NPC.wet) + { + NPC.noGravity = true; + CurrentBehavior = PreviousBehavior; + } + } + private void Kaboom() { if (Main.netMode != NetmodeID.MultiplayerClient) @@ -395,7 +461,7 @@ namespace CalamityMod.NPCs.SunkenSea NPC.GetSource_FromThis(), NPC.Center, Vector2.Zero, - ModContent.ProjectileType(), + ProjectileType(), NPC.damage, 10f, Main.myPlayer); @@ -405,9 +471,6 @@ namespace CalamityMod.NPCs.SunkenSea // a dedicated server doesn't need to load these. if (!Main.dedServ) { - // HI XYK! - // HI MEMES! - for (int i = 0; i < 10; i++) { Dust dust = Dust.NewDustPerfect(NPC.Center, 278, new Vector2(8, 8).RotatedByRandom(100) * Main.rand.NextFloat(0.2f, 1f), 0, default, Main.rand.NextFloat(0.9f, 1.1f)); @@ -433,95 +496,6 @@ namespace CalamityMod.NPCs.SunkenSea NetUpdate(); } - /// - /// Finds a valid target for this NPC. - /// - /// Whether or not it has a found a valid target. - private bool FindsTarget() - { - // When the NPC already had a valid target, - // consider it null if it's not at a desired distance anymore. - if (PlayerTarget is not null) - { - if (NPC.Center.Distance(PlayerTarget.Center) > TargetDistanceDetection) - { - PlayerTarget = null; - return false; - } - - return true; - } - - // Finds the closest target. - NPC.TargetClosest(false); - PlayerTarget = Main.player[NPC.target]; - - // If there was a target but not at a desired distance, we consider there was no target. - if (PlayerTarget is not null && NPC.Center.Distance(PlayerTarget.Center) > TargetDistanceDetection) - { - PlayerTarget = null; - return false; - } - - return true; - } - - /// - /// Creates a list of points that constitutes the grid which the A* algorithm will use. - /// - private List GetPathGrid() - { - List grid = new(); - - Point topLeftCorner = CalamityUtils.ToSafeTileCoordinates(NPC.position + new Vector2(-IdleMovementMaxRange, -IdleMovementMaxRange)); - Point bottomRightCorner = CalamityUtils.ToSafeTileCoordinates(NPC.position + new Vector2(IdleMovementMaxRange, IdleMovementMaxRange)); - - for (int coordY = topLeftCorner.Y; coordY <= bottomRightCorner.Y; coordY++) - { - for (int coordX = topLeftCorner.X; coordX <= bottomRightCorner.X; coordX++) - { - Point point = new(coordX, coordY); - - if (Main.tile[point].IsTileSolid() || Main.tile[point].LiquidAmount != 255 || !AdjacentPointsValid(point)) - continue; - - grid.Add(point); - } - } - - return grid; - } - - /// - /// Checks whether or not path point is valid depending on its adjacent points. - /// - private bool AdjacentPointsValid(Point point) - { - foreach (var direction in Directions) - { - Point adjacentPoint = new(point.X + (int)direction.X, point.Y + (int)direction.Y); - - if (Main.tile[adjacentPoint].IsTileSolid()) - return false; - - adjacentPoint = new(point.X + (int)(direction.X * 2f), point.Y + (int)(direction.Y * 2f)); - - if (Main.tile[adjacentPoint].IsTileSolid()) - return false; - } - - return true; - } - - /// - /// Syncs to the server. - /// - private void NetUpdate() - { - NPC.netUpdate = true; - NPC.netSpam = 0; - } - #endregion #region Drawing & Animation @@ -557,7 +531,10 @@ namespace CalamityMod.NPCs.SunkenSea Vector2 anchorPoint = frame.Size() * 0.5f; SpriteEffects flip = NPC.spriteDirection == -1 ? SpriteEffects.FlipHorizontally : SpriteEffects.None; - spriteBatch.Draw(texture, drawPosition, frame, NPC.GetAlpha(drawColor), NPC.rotation, anchorPoint, NPC.scale, flip, 0f); + 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); return false; } @@ -566,28 +543,22 @@ namespace CalamityMod.NPCs.SunkenSea #region Syncing - public override void SendExtraAI(BinaryWriter writer) + protected override void SendMoreExtraAI(BinaryWriter writer) { writer.Write7BitEncodedInt(AnimationFrames); writer.Write7BitEncodedInt(TimePerAnimationFrame); writer.Write(AnimationLoop); - - writer.Write7BitEncodedInt(PathPositions.Count); - foreach (var position in PathPositions) - writer.WritePackedVector2(position); + writer.Write(MaximumSpeed); + writer.Write7BitEncodedInt(RandomIdleMovementUnlikeliness); } - public override void ReceiveExtraAI(BinaryReader reader) + protected override void ReceiveMoreExtraAI(BinaryReader reader) { AnimationFrames = reader.Read7BitEncodedInt(); TimePerAnimationFrame = reader.Read7BitEncodedInt(); AnimationLoop = reader.ReadBoolean(); - - List receivedPathPositions = new(); - int receivedCount = reader.Read7BitEncodedInt(); - for (int i = 0; i < receivedCount; i++) - receivedPathPositions.Add(reader.ReadPackedVector2()); - PathPositions = receivedPathPositions; + MaximumSpeed = reader.ReadSingle(); + RandomIdleMovementUnlikeliness = reader.Read7BitEncodedInt(); } #endregion diff --git a/NPCs/SunkenSea/Sharkoon.png b/NPCs/SunkenSea/Sharkoon.png index c49606738c..44b0698b16 100644 Binary files a/NPCs/SunkenSea/Sharkoon.png and b/NPCs/SunkenSea/Sharkoon.png differ diff --git a/NPCs/SunkenSea/SunkenSeaNPC.cs b/NPCs/SunkenSea/SunkenSeaNPC.cs new file mode 100644 index 0000000000..9360ea5eb0 --- /dev/null +++ b/NPCs/SunkenSea/SunkenSeaNPC.cs @@ -0,0 +1,450 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Microsoft.Xna.Framework; +using Terraria; +using Terraria.DataStructures; +using Terraria.GameContent.Bestiary; +using Terraria.ID; +using Terraria.ModLoader; +using static Terraria.Utilities.NPCUtils; + +namespace CalamityMod.NPCs.SunkenSea +{ + /// + /// An abstract class that gives an NPC the memebers needed to be a Sunken Sea NPC.
+ /// These have the ability to hunt both players and NPCs, and also have a list of NPCs they hunt and avoid. + ///
+ public abstract class SunkenSeaNPC : ModNPC + { + #region Fields & Properties + + /// + /// A list which stores the NPC's IDs that this creature hunts. + /// + protected abstract List HuntNPCs { get; } + + /// + /// A list which stores the NPC's IDs that this creature avoids. + /// + protected abstract List AvoidNPCs { get; } + + /// + /// Since a lot of these NPCs change behaviors a lot, this abstract class provides an property to store and trigger behaviors.
+ /// Automatically resets and to not cause errors. + ///
+ protected Action CurrentBehavior + { + get => _currentBehavior; + set + { + PreviousBehavior = _currentBehavior; + PathfindingPoints = null; + PathTimer = 0f; + OnBehaviorChange(value); + _currentBehavior = value; + NetUpdate(); + } + } + private Action _currentBehavior; + + /// + /// The previous behavior that was used for . + /// + protected Action PreviousBehavior { get; private set; } + + /// + /// The current NPC that this creature has detected as prey. + /// + protected NPC CurrentPrey + { + get => _currentPrey; + private set + { + if (value != _currentPrey && value != null) + OnPreyDetection(value); + + _currentPrey = value; + } + } + private NPC _currentPrey; + + /// + /// The current NPC that this creature has detected as a predator. + /// + protected NPC CurrentPredator + { + get => _currentPredator; + private set + { + if (value != _currentPredator && value != null) + OnPredatorDetection(value); + + _currentPredator = value; + } + } + private NPC _currentPredator; + + /// + /// The current Player that this creature has detected. + /// + protected Player CurrentPlayer + { + get => _currentPlayer; + private set + { + if (value != _currentPlayer && value != null) + OnPlayerDetection(value); + + _currentPlayer = value; + } + } + private Player _currentPlayer; + + /// + /// The nearest entity detected, could be an NPC or Player. + /// + protected Entity NearestEntity { get; private set; } + + /// + /// Whether or not the creature has detected anything at all. + /// + protected bool HasAnyTargets => CurrentPrey != null || CurrentPredator != null || CurrentPlayer != null; + + /// + /// The distance detection radius.
+ /// Defaults to 300 pixels. + ///
+ protected float DetectionDistance { get; set; } = 300f; + + /// + /// The direction of the cone used to detect targets.
+ /// Defaults to times the direction.
+ /// When set, it normalizes the vector. + ///
+ protected Vector2 ConeDetectionDirection + { + get => _coneDetectionDirection; + set + { + _coneDetectionDirection = value.SafeNormalize(Vector2.UnitX * NPC.direction); + NetUpdate(); + } + } + private Vector2 _coneDetectionDirection; + + /// + /// How open the cone detection is -- given an angle.
+ /// Defaults to 45 degrees. + ///
+ protected float ConeDetectionAngle { get; set; } = MathHelper.ToRadians(45f); + + /// + /// When a this creature has lost sight of a target, it'll still have a sense of permanence.
+ /// This means that, even if it can't see it, it can know it's there.
+ /// This property states how much seconds it can know it's there.
+ /// Defaults to 3 seconds. + ///
+ protected virtual float PermanenceSenseTime => CalamityUtils.SecondsToFrames(3f); + + private int _permanenceSenseTimer; + + /// + /// A lot of these Sunken Sea creatures use the pathfinding algorithm,
+ /// so this abstract class provides a so you can store the paths.
+ /// Defaults to . + ///
+ protected List PathfindingPoints { get; set; } + + /// + /// To decide how to follow the , we use this timer that iteratres through all the points.
+ /// Depending on the speed given to the timer, it'll follow the path faster or slower. + ///
+ protected float PathTimer { get; set; } + + protected Vector2 CurrentlyFollowedPathPoint { get; private set; } + + private bool _hasSpawned; + + #endregion + + #region ModNPC Overrides + + public sealed override void SetStaticDefaults() + { + NPCID.Sets.UsesNewTargetting[Type] = true; + NPCID.Sets.TakesDamageFromHostilesWithoutBeingFriendly[Type] = true; + ExtraSetStaticDefaults(); + } + + public sealed override void OnSpawn(IEntitySource source) { } + + public override void SetBestiary(BestiaryDatabase database, BestiaryEntry bestiaryEntry) + { + bestiaryEntry.Info.AddRange(new IBestiaryInfoElement[] + { + new FlavorTextBestiaryInfoElement($"Mods.CalamityMod.Bestiary.{Name}") + }); + } + + public sealed override void AI() + { + if (!_hasSpawned) + { + CreatureOnSpawn(); + _coneDetectionDirection = Vector2.UnitX * NPC.direction; + _hasSpawned = true; + NetUpdate(); + } + + UpdateTargets(); + + CreatureAI(); + } + + #endregion + + #region Methods + + /// + /// Same function as , and since that one's for safety purposes,
+ /// this method serves the same. + ///
+ protected virtual void ExtraSetStaticDefaults() { } + + /// + /// Same function as , but this one actually syncs to the server. + /// + protected virtual void CreatureOnSpawn() { } + + /// + /// A method that is called on every frame, to put your actual enemy AI. + /// + protected virtual void CreatureAI() { } + + /// + /// A method that is triggered when this NPC's behavior is changed. + /// + protected virtual void OnBehaviorChange(Action newBehavior) { } + + /// + /// A method that is triggered when this creature has detected a prey. + /// + protected virtual void OnPreyDetection(NPC prey) { } + + /// + /// A method that is triggered when this creature has detected a predator. + /// + protected virtual void OnPredatorDetection(NPC predator) { } + + /// + /// A method that is triggered when this creature detects a player. + /// + protected virtual void OnPlayerDetection(Player player) { } + + /// + /// Whether or not a detected player is valid to be set as a target given some conditions. + /// + 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; + } + + /// + /// Whether or not a detected NPC is valid to be set as a target given some conditions. + /// + 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; + } + + /// + /// A method that finds and updates the current detected targets of this creature. + /// + 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)) + CurrentPredator = searchResults.NearestNPC; + + else if (HuntNPCs.Contains(searchResults.NearestNPC.type)) + CurrentPrey = searchResults.NearestNPC; + + if (searchResults.NearestNPCDistance < searchResults.NearestTankDistance) + NearestEntity = searchResults.NearestNPC; + } + + NetUpdate(); + } + else + { + _permanenceSenseTimer++; + if (_permanenceSenseTimer > PermanenceSenseTime) + { + CurrentPlayer = null; + NearestEntity = null; + CurrentPredator = null; + CurrentPrey = null; + _permanenceSenseTimer = 0; + } + } + } + + #endregion + + #region Helper Methods + + /// + /// A quickhand method to make a path with the A* pathfidning algorithm. + /// + protected void MakePath(Vector2 destination, float? range = null) + { + range ??= DetectionDistance; + var grid = CalamityUtils.AStar.MakeGenericGrid(NPC.Center, (float)range); + + if (!grid.Contains(destination.ToTileCoordinates())) + return; + + PathfindingPoints = CalamityUtils.AStar.GetPath(grid, NPC.Center, destination); + NetUpdate(); + } + + /// + /// A quickhand method to make a path with the A* pathfidning algorithm. + /// + protected void MakePath(Vector2 destination, List grid) + { + if (!grid.Contains(destination.ToTileCoordinates())) + return; + + PathfindingPoints = CalamityUtils.AStar.GetPath(grid, NPC.Center, destination); + NetUpdate(); + } + + /// + /// A quickhand method to follow a path found. + /// + protected void GenericPathFollowing(float acceleration, float pathFollowingSpeed, bool conditionToFinishFollowing) + { + CurrentlyFollowedPathPoint = PathfindingPoints[(int)MathF.Floor(PathTimer)]; + NPC.velocity += NPC.DirectionTo(CurrentlyFollowedPathPoint) * acceleration; + PathTimer += pathFollowingSpeed; + PathTimer = MathF.Min(PathTimer, PathfindingPoints.Count - 1); + if (conditionToFinishFollowing) + { + PathfindingPoints = null; + PathTimer = 0f; + NetUpdate(); + } + } + + /// + /// A quick method to check whether this NPC has line of sight with something. + /// + protected bool HasLineOfSight(Vector2 position) => Collision.CanHitLine(NPC.Center, 0, 0, position, 0, 0); + + /// + /// A quickhand method to check if the NPC has finished following the path. + /// + /// + protected bool FinishedPathfinding() + => NPC.DistanceSQ(PathfindingPoints[^1]) < 80f * 80f || + NPC.DistanceSQ(CurrentlyFollowedPathPoint) > 240f * 240f || + PathfindingPoints[^1] == CurrentlyFollowedPathPoint && NPC.velocity == Vector2.Zero; + + #endregion + + #region Syncing + + /// + /// A quick method to both do and set .
+ /// Defaults to 0. + ///
+ protected void NetUpdate(int netSpam = 0) + { + NPC.netUpdate = true; + NPC.netSpam = netSpam; + } + + public sealed 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.Write(PathTimer); + + writer.Write(_hasSpawned); + + SendMoreExtraAI(writer); + } + + public sealed 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()); + PathTimer = reader.ReadSingle(); + + _hasSpawned = reader.ReadBoolean(); + + ReceiveMoreExtraAI(reader); + } + + /// + /// Same function as , but since that one already sends information and to avoid accidents,
+ /// is and instead this is available. + ///
+ protected virtual void SendMoreExtraAI(BinaryWriter writer) { } + + /// + /// Same function as , but since that one already sends information and to avoid accidents,
+ /// is and instead this is available. + ///
+ protected virtual void ReceiveMoreExtraAI(BinaryReader reader) { } + + #endregion + } +} diff --git a/Projectiles/Enemy/SharkoonExplosion.cs b/Projectiles/Enemy/SharkoonExplosion.cs index 960df676d1..c672ea04e8 100644 --- a/Projectiles/Enemy/SharkoonExplosion.cs +++ b/Projectiles/Enemy/SharkoonExplosion.cs @@ -13,6 +13,7 @@ namespace CalamityMod.Projectiles.Enemy public override void SetDefaults() { Projectile.hostile = true; + Projectile.friendly = true; Projectile.width = Projectile.height = Sharkoon.ExplosionRadius * 2; Projectile.timeLeft = 2; } diff --git a/Utilities/MathematicalUtils.cs b/Utilities/MathematicalUtils.cs index e31fb93668..47c72cfafb 100644 --- a/Utilities/MathematicalUtils.cs +++ b/Utilities/MathematicalUtils.cs @@ -401,6 +401,12 @@ namespace CalamityMod return pathfinding.FindPath(); } + public static List GetPath(List grid, Vector2 start, Vector2 goal) + { + var pathfinding = new AStar(grid, start.ToTileCoordinates(), goal.ToTileCoordinates()); + return pathfinding.FindPath(); + } + private List FindPath() { while (openList.Count > 0) @@ -464,6 +470,50 @@ namespace CalamityMod return neighbors; } + + public static List MakeGenericGrid(Vector2 position, float size, Func adjacentTileValidation = null) + { + adjacentTileValidation ??= GenericAdjacentTileValidation; + + List grid = new(); + + Point topLeftCorner = ToSafeTileCoordinates(position + new Vector2(-size, -size)); + Point bottomRightCorner = ToSafeTileCoordinates(position + new Vector2(size, size)); + + for (int coordY = topLeftCorner.Y; coordY <= bottomRightCorner.Y; coordY++) + { + for (int coordX = topLeftCorner.X; coordX <= bottomRightCorner.X; coordX++) + { + Point point = new(coordX, coordY); + + if (Main.tile[point].IsTileSolid() || Main.tile[point].LiquidAmount != 255 || !adjacentTileValidation.Invoke(point)) + continue; + + grid.Add(point); + } + } + + return grid; + } + + private static bool GenericAdjacentTileValidation(Point point) + { + Vector2[] adjacents = new Vector2[12] + { + Vector2.UnitX, -Vector2.UnitX, Vector2.UnitY, -Vector2.UnitY, + new(1f, 1f), new(1f, -1f), new(-1f, -1f), new(-1f, 1f), + Vector2.UnitX * 2f, -Vector2.UnitX * 2f, Vector2.UnitY * 2f, -Vector2.UnitY * 2f + }; + + foreach (var adjacent in adjacents) + { + Point adjacentPoint = new(point.X + (int)adjacent.X, point.Y + (int)adjacent.Y); + if (Main.tile[adjacentPoint].IsTileSolid()) + return false; + } + + return true; + } } #endregion