quhluh

spawning and eating hamburgers code

Mar 29th, 2023
325
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. public class HamburgerGame : MonoBehaviour
  4. {
  5. public GameObject hamburgerPrefab; // hamburger prefab to spawn
  6. public float spawnRate = 1.0f; // rate at which hamburgers spawn
  7. public float moveSpeed = 5.0f; // speed at which hamburgers move
  8. public int score = 0; // player's score
  9. public int lives = 3; // number of lives the player has
  10.  
  11. private float spawnTimer; // timer for spawning hamburgers
  12.  
  13. void Update()
  14. {
  15. // decrement spawn timer
  16. spawnTimer -= Time.deltaTime;
  17.  
  18. // if spawn timer is less than or equal to 0, spawn a hamburger
  19. if (spawnTimer <= 0.0f)
  20. {
  21. SpawnHamburger();
  22. spawnTimer = 1.0f / spawnRate;
  23. }
  24.  
  25. // move all hamburgers in scene
  26. foreach (GameObject hamburger in GameObject.FindGameObjectsWithTag("Hamburger"))
  27. {
  28. hamburger.transform.Translate(Vector3.left * moveSpeed * Time.deltaTime);
  29.  
  30. // check if hamburger is out of bounds and destroy it
  31. if (hamburger.transform.position.x < -10.0f)
  32. {
  33. Destroy(hamburger);
  34. lives--;
  35. }
  36. }
  37.  
  38. // check if player has pressed the space key to eat a hamburger
  39. if (Input.GetKeyDown(KeyCode.Space))
  40. {
  41. // get list of all hamburgers in scene
  42. GameObject[] hamburgers = GameObject.FindGameObjectsWithTag("Hamburger");
  43.  
  44. // check if player is close enough to eat a hamburger
  45. foreach (GameObject hamburger in hamburgers)
  46. {
  47. if (Vector3.Distance(transform.position, hamburger.transform.position) < 2.0f)
  48. {
  49. // destroy hamburger and increase score
  50. Destroy(hamburger);
  51. score++;
  52. }
  53. }
  54. }
  55.  
  56. // check if player has run out of lives
  57. if (lives <= 0)
  58. {
  59. Debug.Log("Game Over!");
  60. enabled = false;
  61. }
  62. }
  63.  
  64. // spawn a hamburger at a random position along the y-axis
  65. void SpawnHamburger()
  66. {
  67. float y = Random.Range(-5.0f, 5.0f);
  68. Instantiate(hamburgerPrefab, new Vector3(10.0f, y, 0.0f), Quaternion.identity);
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment