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
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.
Like this article? We recommend

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020