I have created a projectile script which includes its damage, lifetime and penetrate level. However, it can only check if the character is an enemy, which means I will have to create a script similar to this one to check if the character is the player. I plan to make this script usable by both player and enemies. I am thinking of create an enum or bool in the script for the bullet to know who is shooting the projectile. It would be cool if you guys have any better solutions.
Make player and enemy both inherit from a “Unit” script or something like that, that way it’s easier to apply damage and do all the calculations without overcomplicating it with enums and whatnot. You just need to check if it’s a “Unit” and if yes, do damage.
If you’re saying that you have an Enemy class and a Player class, both of which inherit from Character, and your rule is basically that a projectile won’t hit Characters of the type that fired it (ie. Enemy projectiles won’t hit other Enemy objects), then you can do something like this:
public Character Owner; // set this when a Character spawns the projectile
private void OnTriggerEnter2D(Collider2D other) {
Character c = other.GetComponent<Character>();
// if the other object is a character
if(c != null){
// compare the target's character type to the projectile owner's character type
bool differentCharacterTypes = c.GetType() != Owner.GetType();
if(differentCharacterTypes){
c.TakeDamage(Damage);
if(!canGoThroughTarget){
DestroyProjectile();
}
}
}
else if(other.CompareTag("Wall")){
if(!canGoThroughWalls){
DestroyProjectile();
}
}
}
This gives you more fine-grain control for what types can interact. If you happen to want friendly fire for certain projectiles, it would be easy to change the logic per projectile.
Another approach is to use object layers for Players and Enemys and Walls. In the Physics2D project settings you can configure that the Enemy layer does not collide with other objects in that layer, and set the projectile object to the appropriate layer when spawned. Then you don’t need to do additional checks, the physics system will only call OnTriggerEnter2D when there’s a relevant collision.
Yet another approach is to do your physics overlap checks each frame manually, using a LayerMask to pick up on whatever layers you want, the LayerMask could be supplied or influenced by the owner when spawning the projectile.