Home > Articles > Programming > C#

Building Breakernoid in MonoGame, Part 2

📄 Contents

  1. The Ball: Basic Movement / Width/Height Property in GameObject / The Ball: Bouncing Off Walls
  2. Paddle Collision / Blocks
  • Print
  • + Share This
  • 💬 Discuss
This is the second of four articles on how to create a clone of classic brick-breaking games using C# and MonoGame. In this part, Sanjay Madhav (author of Game Programming Algorithms and Techniques) guides you through the physics of ball movement and collisions with the paddle and blocks.

This is the second article of a series in which you build a clone of classic brick-breaking games called Breakernoid. At the end of Part 1, you ended up with a rough framework with a base GameObject class and a paddle that you could move using the arrow keys.

In this part, you'll add in a bouncing ball and some bricks that can be destroyed with the ball. But before that, you can fix it so you can't move the paddle off of the screen.

Fixing this issue is actually pretty straightforward. All you need to do is to make sure that the paddle isn't moving past the boundary in Paddle.Update.

You can't just check against 0 or 1024 because the paddle has a width. There's also a 32-pixel-wide border on the left/right sides of the screen, so you want to stop the paddle before it goes past it.

You want to clamp position.X so it's between 32 + texture.Width / 2 and 992 - texture.Width / 2. And it turns out that there's a function for clamping values.

In Paddle.Update, after you check the input, but before base.Update, add this:

position.X = MathHelper.Clamp(position.X,
                              32 + texture.Width / 2,
                              992 - texture.Width / 2);

If you want to be flexible, it is better to not rely on the fact that the window resolution is 1024x768, and the border is 32 pixels wide. For simplicity, I'll leave the numbers hard-coded, even though it is not a practice I generally recommend.

In any event, once you add this code, you should no longer be able to move the paddle off the screen.

The Ball: Basic Movement

Now you'll create a ball that bounces around the screen. Create a new class called Ball that inherits from GameObject. The easiest way to do this is to copy the Paddle.cs file and rename it to Ball.cs. Then change every instance of Paddle to Ball.

For the Update function, remove everything other than the base.Update call. Keep the speed member variable because you'll also need a speed for the ball.

Next, you need to add a variable that represents the direction the ball is travelling. For this, you'll use a vector.

Because the game is 2D, you'll want a vector that has two components: X and Y. This corresponds to the Vector2 class in MonoGame. You'll also specifically use what's known as a unit vector, which means that sqrt(X*X + Y*Y) == 1.

Add a new member variable in Ball that's a public Vector2 called direction. You want to initialize it to the value (0.707f, -0.707f), which corresponds to travelling diagonally up and to the right.

The code will look like this:

public Vector2 direction = new Vector2(0.707f, -0.707f);

If you've ever taken a physics class, you know that if there's no acceleration, you can calculate a position with the following equation:

position = initial_position + velocity * t

You'll be doing something very similar in Ball.Update. In this case, velocity is the direction multiplied by the speed. And for the time value t, you'll use deltaTime, which translates to this:

position += direction * speed * deltaTime;

This equation states that the position of the ball is updated on a particular frame based on the velocity multiplied by the delta time.

Now that you have a Ball class, you can create an instance of a ball. Go back to Game1.cs and (as you created and loaded the paddle member variable) do the same with a ball member variable.

For now, initialize the position of the ball to be identical to that of the paddle. Once you make this ball member variable, you need to update it in Game1.Update and draw it in Game1.Draw.

If you run the game, you should now see the ball spawn and quickly move up to the top right of the window, as shown in the following figure:

If you think the ball is moving too quickly, it's very easy to fix. Just change the speed member variable in Ball.cs; I recommend 350. Of course, right now the ball doesn't bounce off the walls. But before you fix it, there's one small thing you should add to GameObject.

Width/Height Property in GameObject

Grabbing the width and height of a particular game object is something you have to do very regularly. Because texture is a protected variable, an outside class can't grab the width from texture directly.

To fix this issue, you'll use a property that is the C# way of creating a getter and/or setter.

The syntax for a property is pretty straightforward. If you open up GameObject.cs, you can add the following Width property in the member data part of the class:

public float Width
{
   get { return texture.Width; }
}

The cool thing about properties is that the caller can use them as if they were member variables. So, for example, it would be totally valid to just write out ball.Width, even though it's running some additional code behind the scenes!

Once you have the Width property, go ahead and add a similar property for the height of the GameObject, as well. With these properties, you can now make the ball bounce.

The Ball: Bouncing Off Walls

Although you could put the code for bouncing into Ball.cs, it will make things easier if you put it in Game1.cs because you have access to all the other objects in the game from here.

Create a new protected void function in Game1 called CheckCollisions. You want to call this function in Game1.Update after the ball.Update call but before base.Update.

There are two steps to bouncing: you need to figure out whether the ball hit the wall and then change its direction if it did. Both these steps aren't actually that challenging.

To figure out whether the ball hit the wall, you need to determine whether the distance between the wall and the ball is less than the radius of the ball. If it is, you know that they intersect.

Because the walls are parallel to the x- and y axes, respectively, it is pretty simple. To check against the left or right wall, the pseudocode looks as follows:

abs(ball_x_position - wall_x_pos) < ball_radius

And for the top wall, use the y position instead. In this case, the radius of the ball corresponds to Width / 2, and you can get an absolute value using Math.Abs.

If you remember that the left wall is at 32 and the right wall is at 992, you can then add checks for the left/right wall like so:

float radius = ball.Width / 2;
if (Math.Abs(ball.position.X - 32) < radius)
{
   // Left wall collision
}
else if (Math.Abs(ball.position.X - 992) < radius)
{
   // Right wall collision
}

Add a similar check for the top wall (which is at y = 32).

Once you have these checks, you need to adjust the direction in which the ball is traveling when an intersection occurs. Because the walls are parallel to the coordinate axes, this is simple.

If the ball hits the left or right wall, simply negate the X component of the direction. Similarly, if the ball hits the top wall, negate the Y component.

If you run the game now, the ball will bounce off the walls a few times before it goes off the bottom of the screen. You can handle the "lose" condition in which the ball goes off the bottom of the screen without hitting the paddle.

To check for this, see whether the Y position of the ball is greater than 768 + ball_radius. When this happens, just reset the position of the ball and paddle back to their original locations, as well as reset the direction of the ball so it faces toward the top right again. Put this reset functionality in a LoseLife function in Game1.cs.

While you're adding this code, you should also adjust the position of the ball so that it doesn't spawn at the exact position of the paddle.

Instead, make it so that the ball spawns at ball.Height + paddle.Height above the center of the paddle. Remember that because y=0 is at the top of the screen, this will be paddle.position.Y - ball.Height - paddle.Height.

This change is necessary to make sure that you don't spawn the ball at a spot that collides with the paddle. Make sure that you set the ball to this position both on the initial spawn and in LoseLife.

In any event, it should now be set up so that when the ball goes off the bottom of the screen, it respawns in the middle.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus