BallGame component

Now is a good time to add the BallGame component to our ball game.

The BallGame component is associated with each separate ball game. It uses the ThrowControl component to determine when the show is done and if the ball hit the goal. Then, it invokes a Won or Lost event accordingly.

We'll add a BallGame component to our Boxball game. When we add more games, such as basketball and football, they'll also have a BallGame component:

  1. In the Project Assets/ARBallPlay/Scripts/ folder, create a C# script named BallGame.
  2. Add the component to the BoxballGame object.
  3. And then open it for editing.

The full script is as follows:

File: BallGame.cs
using UnityEngine; using UnityEngine.Events; public class BallGame : MonoBehaviour { public ThrowControl BallThrowControl; public GameObject CourtGameObject; public CollisionBehavior GoalCollisionBehavior; public UnityEvent OnGoalWon; public UnityEvent OnGoalLost; private bool wonGoal; void Start() { BallThrowControl.OnReset.AddListener(OnBallReset); GoalCollisionBehavior.OnHitGameObject.AddListener(CheckGoal); } void OnBallReset() { if (wonGoal) { OnGoalWon.Invoke(); } else { OnGoalLost.Invoke(); } //Resets the game GoalCollisionBehavior.ResetCollision(); wonGoal = false; } void CheckGoal(GameObject hitGameObject) { if (hitGameObject == BallThrowControl.gameObject) { wonGoal = true; } } }

The BallGame component reference's the game's ThrowControl in order to determine that the game object in the goal is actually our ball (conceivably, the event could have come from anywhere). If so, we set wonGoal to true.

As explained in the beginning of the chapter, the OnBallReset will invoke an OnGoalWon or OnGoalLost event for the GameController to update the scoreboards. We do this in reset rather than when the goal first detected for effect and to give the ball a chance to bounce around the court.

Save the script. Then do the following steps:

  1. Drag the BallGame script onto the BoxballGame object as a component.
  2. Drag the Ball object onto the Ball Throw Control slot.
  3. Drag the Court object from Hierarchy onto the Ball Game component's Court Game Object slot.
  4. Drag the GoalCollider onto the Goal Collision Behavior slot.

If you Play at this point, the behavior of the game has not changed, but now we're ready to start keeping score.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.174.239