Ball.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.ComponentModel;
  3. using UnityEngine;
  4. using Random = UnityEngine.Random;
  5. namespace Assets.Pong
  6. {
  7. public class Ball : MonoBehaviour
  8. {
  9. public float speed = 5f;
  10. public event EventHandler<Side> GoalScored;
  11. bool scored;
  12. public void Recenter()
  13. {
  14. var component = GetComponent<Rigidbody>();
  15. component.velocity = Vector3.zero;
  16. component.transform.position = Vector3.zero;
  17. scored = false;
  18. }
  19. public void Kickoff()
  20. {
  21. float sx = Random.Range(0, 2) == 0 ? -1 : 1;
  22. float sz = Random.Range(0, 2) == 0 ? -1 : 1;
  23. GetComponent<Rigidbody>().velocity = new Vector3(speed * sx, 0f, speed * sz);
  24. }
  25. private void Update()
  26. {
  27. var xPosition = GetComponent<Rigidbody>().transform.position.x;
  28. if (xPosition > 15 && !scored)
  29. {
  30. scored = true;
  31. GoalScored.Invoke(this, Side.Right);
  32. }
  33. else if (xPosition < -15 && !scored)
  34. {
  35. scored = true;
  36. GoalScored.Invoke(this, Side.Left);
  37. }
  38. }
  39. }
  40. }