GunController.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using UnityEngine;
  2. using UnityEngine.InputSystem;
  3. public class GunController : MonoBehaviour
  4. {
  5. [SerializeField]
  6. private Transform muzzle;
  7. [SerializeField]
  8. private InputActionProperty trigger;
  9. public float shotsPerSecond = 1.0f;
  10. public float projectileSpeed = 1.0f;
  11. public float projectileLifeTime = 1.0f;
  12. public GameObject projectileObject;
  13. private float lastShotTimestamp;
  14. private float lastTriggerPress;
  15. // Start is called once before the first execution of Update after the MonoBehaviour is created
  16. void Start()
  17. {
  18. lastShotTimestamp = -1 * (1 / shotsPerSecond);
  19. }
  20. // Update is called once per frame
  21. void Update()
  22. {
  23. if (trigger.action.WasPressedThisFrame() && Time.time - lastShotTimestamp >= 1/shotsPerSecond)
  24. {
  25. GameObject spawnedObject = Instantiate(projectileObject);
  26. Projectile projectileScript = spawnedObject.GetComponent<Projectile>();
  27. GameObject dynamicContainer = GameObject.Find("_Dynamic");
  28. if (dynamicContainer != null)
  29. {
  30. spawnedObject.transform.parent = dynamicContainer.transform;
  31. }
  32. spawnedObject.transform.position = muzzle.position;
  33. spawnedObject.transform.rotation = transform.rotation;
  34. if (projectileScript != null) {
  35. projectileScript.maxLifeTime = projectileLifeTime;
  36. projectileScript.speed = projectileSpeed;
  37. }
  38. lastShotTimestamp = Time.time;
  39. Debug.Log("Shoot");
  40. }
  41. }
  42. }