I am working on a projectile shattering logic. When bullet hits the target it should split into multiple sub-bullets. Currently just trying to make a prototype work with 1 single shard created after hitting the mark:
public partial class Projectile : Area2D
{
public int Speed { get; set; } = 500;
private bool _isDead = false;
public List<ulong> IgnoredTargets = new List<ulong>();
public override void _Ready()
{
// Connect the bullet's collision signal to the onBulletCollision method
BodyEntered += OnBodyEntered;
}
public override void _Process(double delta)
{
if (_isDead)
return;
// Move the bullet forward
var distance = Speed * (float)delta;
Vector2 velocity = new Vector2(distance, 0).Rotated(Rotation);
Position += velocity;
}
private void OnBodyEntered(Node body)
{
var targetId = ((Node2D)body).GetInstanceId();
// prevent same projectile hitting same target more than once
if (IgnoredTargets.Contains(targetId))
return;
if (_isDead)
{
GD.PrintErr("Projectile hit something after dying!");
return;
}
IgnoredTargets.Add(targetId);
var shard = (Projectile)this.Duplicate();
shard.IgnoredTargets.AddRange(this.IgnoredTargets);
GetParent().CallDeferred("add_child", shard);
_isDead = true;
QueueFree();
}
}
The problem with this approach is I a keep getting the error messages:
Projectile hit something after dying!
Basically it means that the disposing of the old bullet is not happening!
However if I remove the shatter creation logic:
var shard = (Projectile)this.Duplicate();
shard.IgnoredTargets.AddRange(this.IgnoredTargets);
GetParent().CallDeferred("add_child", shard);
the the error goes away... Could someone explain how to fix the issue? I would like the "old" bullet to be disposed of immediately after spawning several other sub-bullets of the same type (in example above I am creating just 1 shard for testing purposes by duplicating the existing node)
I feel like something is blocking the bullet disposal process so it keeps triggering the error message.. I am keeping track of all the objectss that the bullet has previously collided with using the IgnoredTargets
property which is then passed to a shattered node.. but somehow this does not prevent the issue from happening.