BlasterBullet.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using UnityEngine;
  2. namespace Assets.Scripts.BlasterWeapon
  3. {
  4. internal sealed class BlasterBullet : MonoBehaviour
  5. {
  6. [HideInInspector]
  7. public float Speed = 1;
  8. [HideInInspector]
  9. public float LifeTime = 2f;
  10. public GameObject ImpactEffect;
  11. public GameObject BulletEffect;
  12. public bool DestroyOnCollision = true;
  13. private GameObject _bulletEffect;
  14. private Transform _transform;
  15. private void Start()
  16. {
  17. _bulletEffect = Instantiate(BulletEffect, transform.position, transform.rotation);
  18. _transform = transform;
  19. Destroy(_bulletEffect, LifeTime);
  20. Destroy(gameObject, LifeTime);
  21. }
  22. private void Update()
  23. {
  24. RaycastHit hit;
  25. if (Physics.Raycast(_transform.position, _transform.forward, out hit, Speed * Time.deltaTime * 2))
  26. {
  27. _transform.position = hit.point;
  28. var impactEffect = Instantiate(ImpactEffect, hit.point, new Quaternion());
  29. impactEffect.transform.LookAt(_transform.position + hit.normal);
  30. _bulletEffect.transform.position = hit.point;
  31. Destroy(impactEffect, LifeTime);
  32. if (DestroyOnCollision)
  33. {
  34. Destroy(_bulletEffect);
  35. Destroy(gameObject);
  36. }
  37. }
  38. if (_bulletEffect == null)
  39. return;
  40. _transform.position += _transform.forward * Speed * Time.deltaTime;
  41. _bulletEffect.transform.position = _transform.position;
  42. }
  43. }
  44. }