09. Scoring and Restarting Rounds

Introduction

Currently the game is playable, but scoring a goal results in the puck moving off-screen. We’ll add logic and data to detect when a goal is scored by resetting the position of all objects and assigning points.

Creating the Goal Region Rectangles

Conceptually detecting a goal is simple – whenever the Puck collides with a certain area then a goal has been scored. The first step is to define the goal area. To do this:

  1. Expand GameScreen in Glue
  2. Right-click on Objects
  3. Select “Add Object”
  4. Select the “PositionedObjectList<T>” type
  5. Select “FlatRedBall.Math.Geometry.AxisAlignedRectangle” as the type
  6. Enter Goals as the name

  7. Click OK

Next we’ll add two goal rectangles. To do this:

  1. Right-click on “Goals” and select “Add Object”
  2. Enter the name “LeftGoal” and click OK
  3. Right-click on “Goals” and select “Add Object”
  4. Enter the name “RightGoal” and click OK

Why do goal names matter? In an earlier tutorial we created the wall collision and named them sequentially (Wall1, Wall2, etc). However, the goals are slightly different – our code will test to see which specific goal we’ve collided against. We can’t just loop through goals and perform collision (like we do with walls) – we’re going to specifically test collision between the Puck instance and the LeftGoal and RightGoal to see who should be awarded points when a goal has been scored.

Next, modify the goals values as follows:

LeftGoal:

  • X = -400
  • Width = 1
  • Height = 200

RightGoal:

  • X = 400
  • Width = 1
  • Height = 200

Keeping the PlayerBall Instances in the game

You may have noticed that the PlayerBall instances can move outside of the game screen. To fix this we’ll make the player bounce against the goal areas. Open GameScreen.cs and modify the CollisionActivity method to include a loop for performing collision between the goals and the players as follows:

If you run the game, you will no longer be able to leave the play area with either PlayerBall.

Detecting Goals

Now that we have all of our data and object instances set up, we can write code to detect if a goal has occurred. First we’ll need two variables to keep track of score. Add this code to GameScreen.cs at class scope (outside of any methods):

Next, add logic to detect if the puck has actually entered either of the goals. To do this, add the following code at the end of CollisionActivity:

Next, add the ReactToNewScore method:

Now you can play the game and you’ll notice that when the game resets when the Puck enters a goal.

Conclusion

If you’ve made it this far, congratulations! You now have a fully-playable game…at least, to the point where you can play with friends. There’s still a few more things we’ll do to improve the design and add polish. The next tutorial will cover adding a HUD to display player score.

<- Adding multiple playersScoring HUD ->