using System.Collections; using Ai; using DG.Tweening; using UnityEngine; using Random = UnityEngine.Random; namespace Player { [RequireComponent(typeof(Rigidbody))] public class Bullet : MonoBehaviour { [SerializeField, HideInInspector] private Rigidbody _rigidbody; [SerializeField] private float _speed; [SerializeField] private float _autoDestroy; [SerializeField] private float _damage; [SerializeField] private GameObject _hitObject; [SerializeField] private bool _physicBullet; private Vector3 _direction = Vector3.forward; private bool _isHitObjectNotNull; private float _additionalDamage; private float _critChance; private float _mult = 1f; public float Mult { get { return _mult; } set { _mult = value; } } private void Start() { _isHitObjectNotNull = _hitObject != null; } public void Init(Vector3 direction, float additionalDamage, float critChance, bool toTarget = false) { direction.y = 0; _direction = direction; if (!toTarget) { transform.forward = direction; _rigidbody.velocity = _direction * _speed; } else { transform.DOMove(_direction, _autoDestroy); } _additionalDamage = additionalDamage; _critChance = critChance; if (_autoDestroy > 0) StartCoroutine(AutoDestroy()); } private void OnCollisionEnter(Collision other) { if (!_physicBullet) { Debug.LogErrorFormat("Bullet not a trigget on non physic bullet {0}", name); return; } ProceedBullet(other.gameObject); } private IEnumerator AutoDestroy() { yield return new WaitForSeconds(_autoDestroy); DestroyBullet(); } private void OnValidate() { if (_rigidbody == null) _rigidbody = GetComponent(); } private void OnTriggerEnter(Collider other) { ProceedBullet(other.gameObject); } private void ProceedBullet(GameObject collision) { var obstacle = collision.GetComponent(); if (obstacle != null && (obstacle.Type == GameObstaclesType.LASER || obstacle.Type == GameObstaclesType.SLOW_FLOOR || obstacle.Type == GameObstaclesType.SPIKES_FLOOR)) return; var body = collision.GetComponent(); if (body != null) { var crit = Random.Range(0.01f, 1f); if (crit <= _critChance) body.InstantDestroy((_damage + _additionalDamage) * Mult); else body.SetDamage(_damage + _additionalDamage); } var character = collision.GetComponent(); if (character != null) { float abilityVal = GlobalsVar.gMainAbilities.GetAbilityValueByType(Ability.MainAbilityType.ADD_ARMOR_SHOT); float damage = _damage - _damage * (abilityVal / 100f); character.TakeDamage((int)_damage); } if (_autoDestroy > 0 && (!_physicBullet || character != null || body != null)) DestroyBullet(); } public void DestroyBullet() { if (_isHitObjectNotNull) { var obj = Instantiate(_hitObject); obj.transform.position = transform.position; var bullet = obj.GetComponent(); if (bullet) { SoundsManager.Instance.PlaySound("grenade_explosion"); } BulletManager.Instance.Collection.Remove(this); } Destroy(gameObject); } private void OnEnable() { BulletManager.Instance.Collection.Add(this); } } }