projekt-bombs/Assets/Scripts/src/Ammo/BombController.cs

76 lines
2.2 KiB
C#
Raw Normal View History

2019-06-02 10:00:00 +00:00
using System.Collections;
2019-06-09 20:33:48 +00:00
using src.Managers;
2019-06-02 10:00:00 +00:00
using UnityEngine;
2019-06-09 20:33:48 +00:00
namespace src.Ammo
2019-06-02 10:00:00 +00:00
{
2019-06-09 20:33:48 +00:00
public class BombController : MonoBehaviour, IExplosable
{
public GameObject explosionPrefab;
2019-06-02 10:00:00 +00:00
2019-06-10 14:28:33 +00:00
private readonly BombsUtilManager _bombsUtil = BombsUtilManager.Instance;
2019-06-09 20:33:48 +00:00
private bool _exploded;
2019-06-02 10:00:00 +00:00
2019-06-09 20:33:48 +00:00
// Start is called before the first frame update
void Start()
{
2019-06-10 14:28:33 +00:00
Invoke(nameof(Explode), _bombsUtil.Timer);
2019-06-09 20:33:48 +00:00
}
2019-06-02 10:00:00 +00:00
2019-06-09 20:33:48 +00:00
void Explode()
{
Instantiate(explosionPrefab, transform.position, Quaternion.identity);
2019-06-02 10:00:00 +00:00
2019-06-09 20:33:48 +00:00
GetComponent<SpriteRenderer>().enabled = false;
transform.Find("2DCollider").gameObject.SetActive(false);
2019-06-02 10:00:00 +00:00
2019-06-09 20:33:48 +00:00
StartCoroutine(CreateExplosions(Vector3.down));
StartCoroutine(CreateExplosions(Vector3.left));
StartCoroutine(CreateExplosions(Vector3.up));
StartCoroutine(CreateExplosions(Vector3.right));
2019-06-02 10:00:00 +00:00
2019-06-09 20:33:48 +00:00
_exploded = true;
Destroy(gameObject, 0.3f);
2019-06-10 14:28:33 +00:00
_bombsUtil.RemoveBomb(transform.position);
2019-06-09 20:33:48 +00:00
}
private IEnumerator CreateExplosions(Vector3 direction)
2019-06-02 10:00:00 +00:00
{
2019-06-10 14:28:33 +00:00
for (int i = 1; i < _bombsUtil.Power; i++)
2019-06-02 10:00:00 +00:00
{
2019-06-09 20:33:48 +00:00
RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, i,
1 << 8);
if (!hit.collider)
{
Instantiate(explosionPrefab, transform.position + i * direction,
explosionPrefab.transform.rotation);
}
else
{
2019-06-10 14:28:33 +00:00
var key = hit.collider.GetComponent<IExplosable>();
2019-06-10 14:46:01 +00:00
if(key != null)
{
key.onExplosion();
}
2019-06-09 20:33:48 +00:00
break;
}
2019-06-02 10:00:00 +00:00
}
2019-06-09 20:33:48 +00:00
yield return new WaitForSeconds(0.05f);
2019-06-02 10:00:00 +00:00
}
2019-06-09 20:33:48 +00:00
public void OnTriggerEnter2D(Collider2D other)
2019-06-02 10:00:00 +00:00
{
2019-06-09 20:33:48 +00:00
if (!_exploded && other.CompareTag("Explosion"))
{
onExplosion();
}
2019-06-02 10:00:00 +00:00
}
2019-06-08 12:25:09 +00:00
2019-06-09 20:33:48 +00:00
public void onExplosion()
{
CancelInvoke(nameof(Explode));
Explode();
}
2019-06-08 12:25:09 +00:00
}
2019-06-09 20:33:48 +00:00
}