I am looking at the title of the post and I’m not sure how to answer this. It seems you want to apply knockback to a Unit when a bullet hits them. Your question, though, is about getting hold of the bullet transform before it is destroyed.
I’m going to try and answer the post as a whole.
First, how do plan on doing the actual knockback? The ragdoll is not going to work because it’s just that: a ragdoll. You are going to have very little control over it unless you look into active ragdolls, and that’s a beast I shouldn’t even have mentioned. An animation could work, but will likely not need to know anything about the bullet unless you have some complex blending or procedural stuff happening.
Once you have figured that out, there are a few ways you could do this (with the code we have)
One way would be to have a ‘Knockback’ method on the unit that will do whatever you want to do. You would have to update the BulletProjectile
a little so that it knows which unit it was targeting, but that’s not a big change. It will, however, restrict what you can shoot at (which isn’t so much a problem at the moment 'cos we can only shoot Units anyway, but the projectile isn’t applying that restriction, the ShootAction is).
You can pass the target unit to the Setup
of the BulletProjectile
private Unit targetUnit;
public void Setup(Vector3 targetPosition, Unit targetUnit)
{
// I am not getting targetPosition from the unit
// transform because we are passing in a different
// target position (so that we don't shoot the feet)
this.targetPosition = targetPosition;
this.targetUnit = targetUnit;
}
Now, when the bullet reaches the target and destroys itself, it can call the ‘Knockback’ method on Unit
if (distanceBeforeMoving < distanceAfterMoving)
{
transform.position = targetPosition;
trailRenderer.transform.parent = null;
// I am passing moveDir to knockback so that the unit
// can know the direction the bullet was travelling in. Could
// be useful for applying directional force, for example
targetUnit.Knockback(moveDir);
Destroy(gameObject);
Instantiate(bulletHitVfxPrefab, targetPosition, Quaternion.identity);
}
Example Knockback
method
public void Knockback(Vector3 knockDirection)
{
// UNTESTED
// Try to move (teleport, really) the unit 1 tile away
// in the direction the bullet is flying
var targetPos = transform.position + (knockDirection * LevelGrid.Instance.GetCellSize());
var targetGridPos = LevelGrid.Instance.GetGridPosition(targetPos);
if (!LevelGrid.Instance.IsValidGridPosition(targetGridPos)) return;
if (!Pathfinding.Instance.IsWalkableGridPosition(targetGridPos)) return;
transform.position = LevelGrid.Instance.GetWorldPosition(targetGridPos);
}
If you definitely want the bullet transform, make the Knockback
accept Transform
instead of Vector3
and pass that instead of moveDir
, but I’m not sure why you would need that. The Knockback
function is called before the bullet gets destroyed, so you will have access to it.