7 /// The controller for the basketball-game logic.
9 public class GameController : MonoBehaviour
11 private State state = State.JumpBall; // A basketball game always starts with a jump ball.
17 /// The single ball for the game.
19 [SerializeField] public Ball ball;
21 [SerializeField] public Hoop PlayerHoop;
22 [SerializeField] public Hoop EnemyHoop;
26 player = new Player { isEnemy = false, controller = this };
27 enemy = new Player { isEnemy = true, controller = this };
28 ball.controller = this;
34 /// Whether this player is the AI-enemy.
36 internal bool isEnemy;
39 /// A back-reference to the containing GameController.
41 internal GameController controller;
45 private Vector2 lastShotPosition;
46 public void Score(Vector2 Rim) {
47 if (Vector2.Distance(lastShotPosition, Rim) >= 1)
50 Debug.Log("Three point");
53 Debug.Log("Two point");
56 private State dribble => isEnemy ? State.EnemyDribble : State.PlayerDribble;
57 private State shoot => isEnemy ? State.EnemyShoot : State.PlayerShoot;
59 public bool HasBall => controller.state == dribble;
62 /// When dribbling, move the ball with the player.
64 /// <param name="handPosition">The position of the hand dribbling the ball.</param>
65 public void Move(Vector2 handPosition)
67 if (controller.state == (isEnemy ? State.EnemyDribble : State.PlayerDribble)) // Make sure they're dribbling.
68 controller.ball.transform.position = handPosition; // TODO: Make this perform a dribbling motion, otherwise it looks like they're travelling.
72 /// Grab the ball if possible given the current game state.
74 /// <param name="handPosition">The position of the hand to attempt grabbing from.</param>
75 /// <returns>Whether or not the ball was able to be picked up.</returns>
76 public bool GrabBall(Vector2 handPosition)
78 // Don't allow the ball to be picked up if someone shot it. Also don't try picking it up if we're already holding it.
79 if (controller.state.IsShot() || controller.state == dribble) return false;
81 // Make sure its within their grab area.
82 if (Vector2.Distance(controller.ball.transform.position, handPosition) > 0.75f) return false;
84 controller.state = dribble;
90 /// Shoot the ball if possible.
92 /// <param name="playerTransform"></param>
93 /// <returns>Whether or not the ball was shot</returns>
94 public bool Shoot(Transform playerTransform)
96 if (controller.state != dribble) return false; // We must be dribbling the ball to shoot it.
97 controller.state = shoot;
98 controller.ball.Shoot(playerTransform);
99 lastShotPosition = playerTransform.position;
104 internal void BallDropped()
120 internal static class GameControllerStateExtensions
122 internal static bool IsShot(this GameController.State state)
124 return state == GameController.State.EnemyShoot || state == GameController.State.PlayerShoot;
127 internal static bool IsDribble(this GameController.State state)
129 return state == GameController.State.EnemyDribble || state == GameController.State.PlayerDribble;