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