Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- namespace _Scripts
- {
- public class ParticleBullet : MonoBehaviour
- {
- public float speed = 5f;
- private Vector3 direction;
- [SerializeField] Collider[] colliders;
- [SerializeField] GameObject[] particleSystems;
- [SerializeField] GameObject hitEffect = null;
- Rigidbody rb;
- private bool active;
- public int bulletPower = 1;
- private float lifeTimer;
- [SerializeField] float lifeTime = 4f;
- private void Awake()
- {
- rb = GetComponent<Rigidbody>();
- }
- void OnEnable()
- {
- lifeTimer = lifeTimer;
- }
- public void SetBullet(Vector3 direction, float speed)
- {
- this.direction = direction;
- this.speed = speed;
- }
- public void SetDirection(Vector3 dir)
- {
- direction = dir.normalized;
- }
- public void SetSpeed(float value)
- {
- speed = value;
- }
- void Update()
- {
- lifeTimer -= Time.deltaTime;
- if (lifeTimer <= 0 && active)
- {
- var newpos = Vector3.forward * 1000;
- transform.position = newpos;
- Activate(false);
- }
- transform.position += direction * (speed * Time.deltaTime);
- RotateTowardsHeading();
- }
- void RotateTowardsHeading()
- {
- if (direction != Vector3.zero)
- {
- Quaternion targetRotation = Quaternion.LookRotation(direction, Vector3.up);
- transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 1000f);
- }
- }
- /// <summary>
- /// Activate/Inactivate Bullet
- /// </summary>
- public void Activate(bool isActive)
- {
- active = isActive;
- rb.detectCollisions = isActive;
- if (colliders != null && colliders.Length > 0)
- {
- for (int i = 0; i < colliders.Length; i++)
- {
- colliders[i].enabled = active;
- }
- }
- if (particleSystems != null && particleSystems.Length > 0)
- {
- for (int i = 0; i < particleSystems.Length; i++)
- {
- particleSystems[i].SetActive(active);
- }
- }
- if (!isActive)
- {
- if (hitEffect != null)
- {
- GameObject obj = ObjectPool.instance.SpawnPrefab(hitEffect);
- obj.transform.position = transform.position;
- obj.transform.rotation = Quaternion.identity;
- }
- ObjectPool.instance.ReturnToPool(gameObject);
- }
- }
- private void OnCollisionEnter(Collision collision)
- {
- Collider collider = collision.collider;
- if (collider.CompareTag("Enemy")
- || collider.CompareTag("Player"))
- {
- // Damage the enemy
- IDamageable damageable = collider as IDamageable;
- if (damageable != null)
- {
- damageable.OnBulletStrike(bulletPower);
- }
- Activate(false);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement