PlayerWeapon.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class PlayerWeapon : MonoBehaviour {
  5. public GameObject bulletPrefab;
  6. public Transform bulletSpawn;
  7. public float bulletSpeed = 30;
  8. public float lifeTime = 3;
  9. // Update is called once per frame
  10. void Update ()
  11. {
  12. if (Input.GetKeyDown(KeyCode.Space))
  13. {
  14. Fire();
  15. }
  16. }
  17. private void Fire()
  18. {
  19. GameObject bullet = Instantiate(bulletPrefab);
  20. Physics.IgnoreCollision(bullet.GetComponent<Collider>(),
  21. bulletSpawn.parent.GetComponent<Collider>());
  22. bullet.transform.position = bulletSpawn.position;
  23. var rot = bullet.transform.rotation.eulerAngles;
  24. bullet.transform.rotation = Quaternion.Euler(rot.x, transform.eulerAngles.y, rot.z);
  25. bullet.GetComponent<Rigidbody>().AddForce(bulletSpawn.forward * bulletSpeed, ForceMode.Impulse);
  26. StartCoroutine(DestroyBulletAfterTime(bullet, lifeTime));
  27. }
  28. private IEnumerator DestroyBulletAfterTime(GameObject bullet, float delay)
  29. {
  30. yield return new WaitForSeconds(delay);
  31. Destroy(bullet);
  32. }
  33. }