private void tryFireBullet() { Enemy[] enemies = FindObjectsOfType <Enemy>(); float minDistanceSquared = range * range; Enemy nearestEnemy = null; foreach (Enemy enemy in enemies) { float distanceSquared = (enemy.gameObject.transform.position - gameObject.transform.position).sqrMagnitude; if (distanceSquared < minDistanceSquared) { nearestEnemy = enemy; minDistanceSquared = distanceSquared; } } if (nearestEnemy == null) { return; } TowerBullet bullet = Instantiate(bulletPrefab); bullet.transform.position = gameObject.transform.position; bullet.target = nearestEnemy.gameObject.transform.position; bullet.source = this; }
public void OnTriggerEnter2D(Collider2D col) { TowerBullet bullet = col.gameObject.GetComponent <TowerBullet>(); if (bullet == null) { return; } health -= 1; if (health <= 0) { Destroy(gameObject); bullet.source.killCount++; GameController.Score += 1; } Destroy(bullet.gameObject); }