My alternative approach to this chapter

Hi guys,

The way that I prevented friendly-fire and lazer-to-lazer collision is as such:

public class Lazer : MonoBehaviour {

Vector3 topLimit,bottomLimit;
public int damage;
public string enemy;

void Start(){
	topLimit = Camera.main.ViewportToWorldPoint(new Vector3(0,1,0));
	bottomLimit = Camera.main.ViewportToWorldPoint(new Vector3(0,0,0));
}

void Update(){
            // destroys itself if go out of the view
	if (transform.position.y > topLimit.y || transform.position.y < bottomLimit.y){
		Destroy(gameObject);
	}
}

    // only destroys itself if what it hit is and enemy
void OnTriggerEnter2D(Collider2D col){
	if (col.gameObject.tag == enemy){
		Destroy (gameObject);
	}
}

}

public class EnemyBehaviour : MonoBehaviour {

public int health;
public GameObject lazer;
public float lazerSpeed;
public float shotsPerSecond;

    /*upon detecting trigger, only takes damage if lazer's enemy is "Enemy". PlayerController have a similar method
       except that enemy tag should be "Player"*/
void OnTriggerEnter2D(Collider2D col){
	Lazer hitLazer = col.gameObject.GetComponent<Lazer>();
	if (hitLazer.enemy == "Enemy"){		
		health -= hitLazer.damage;
	}
	if (health <= 0){
		Destroy(gameObject);
	}
}

The rest is some drag-and-dropping in the editor to make it work

I like your approach.

much simpler than my first attempt.

I simply put just made a IsPlayers boolean on the Laser and then at every hit I check if the collision is a target that is allowed to be hit by that projectile. but yours keep the logic for the laser in the lazer class instead of spreading it out to the enemies or players :slight_smile:

You can also use Unity’s Layer Collision Matrix under Edit>Project Settings>Physics 2D

CollisionMatrix

Kudos for the code tho :beers:

I only used two layers, “enemies” and “friendlies”, because I didn’t see the need for 4 layers (enemy, enemyProjectile, friendly, friendly projectile.)
Was there some logic I missed?

I just did this:

For enemy:

void OnTriggerEnter2D (Collider2D collider) {
playerLaser playerLaser = collider.GetComponent< playerLaser >();

	if (playerLaser) {
		Health -= playerLaser.Damage;
		playerLaser.Hit();
		if (Health <= 0) {
			Destroy(gameObject);
		}
	}
}

for player:

void OnTriggerEnter2D (Collider2D collider) {
enemyLaser enemyLaser = collider.GetComponent< enemyLaser >();

	if (enemyLaser) {
		Health -= enemyLaser.Damage;
		enemyLaser.Hit();
		if (Health <= 0) {
			Destroy(gameObject);
		}
	}
}

I like the way you think and think outside the box.

However there is a big difference between using the collision matrix and code to avoid collision. When you use code the collision still happens but you if statement prevents anything else from happening. When using the coliision matrix the collision is avoided in total. For a small game this is no problem, but it could be for bigger games.

In case of learning to code it is a good exercise for yourself.

Privacy & Terms