Home > Articles > Programming > C#

  • Print
  • + Share This
Like this article? We recommend

Power-Ups: Basics

Now you will add some power-ups. There currently three different power-ups:

  • Ball Catch: When this power-up is active, the ball is caught by the paddle and it is released only when the spacebar is pressed.
  • Multi-Ball: This power-up spawns another ball at the current paddle location.
  • Paddle Size: This power-up increases the width of the paddle. It doesn't stack, so there's only one size increase that's possible.

Power-ups will have a chance of spawning every time a block is destroyed. They will then fall vertically, and if the player picks up the power-up with the paddle before it goes offscreen, they'll get that power-up.

When the player loses a life (which you'll redefine as having 0 balls left), any active power-ups reset.

Before you actually implement the custom functionality for each power-up, you need to add the code that randomly spawns one of the power-ups on occasion.

First, create a new class that inherits from GameObject called PowerUp. In this class, you will want to add an enum that defines the three different types of power-ups (much as you did for BlockColor).

Based on the power-up enum passed to the constructor, set it to either powerup_c (for ball catch), powerup_b (for multi-ball), or powerup_p (for paddle size).

Next, have the PowerUp.Update function increase the Y position based on speed and deltaTime. This will cause the PowerUp to fall once it is spawned.

Once you have this PowerUp class, you need to add a list of power-ups in Game1.cs, much as you did for the blocks.

Next, create a function in Game1 called SpawnPowerUp, which takes a Vector2 called position as a parameter. Don't put anything in this function just yet.

In order to randomly spawn a power-up, you need a pseudo-random number generator. C# has one built in: the Random class.

Add an instance of one as a member variable to Game1:

Random random = new Random();

This also automatically sets the seed based on the clock, so you don't have to pass in a seed like you might in C/C++.

Next, create a double that represents the probability that a power-up spawns when you destroy a block. It has to be a double, not a float.

For now, use 0.2, which means that when you destroy a block, a power-up will spawn 20% of the time.

Then go to the code that destroys blocks. When one is destroyed, use random.NextDouble to get a random double that's between 0.0 and 1.0.

If this double is less than your power-up chance, you should then call SpawnPowerUp and pass in the position of the block that was just destroyed.

Now you can implement SpawnPowerUp. In here, use random.Next(3) to get an integer from 0-2. Take this int, convert it to the PowerUpType enum, create the appropriate PowerUp, set its position to the position that was passed into SpawnPowerUp, and add the PowerUp to the list of power-ups.

Next, you need to add the code that loops through the list of power-ups and draws them, which goes in Game1.Draw.

Likewise, you need to add the code that loops through the list of power-ups and calls Update on each of them; you should do this before the CheckCollisions call in Game1.Update.

Finally, you need to detect whether any of the power-ups have moved offscreen. One way to do this is to create a public bool in the PowerUp class that tracks whether a power-up should be removed. Then in PowerUp.Update, check whether the Y position is off the screen; if it is, set that bool to true.

You can then loop through all the power-ups in a function in Game1 and remove any that have this bool set.

Remember that you can't use a foreach while you're removing elements from the list, so one solution is to use a regular for loop in reverse.

It will look something like this:

for (int i = powerups.Count - 1; i >= 0; i--)
{
   if (powerups[i].shouldRemove)
   {
      powerups.RemoveAt(i);
   }
}

Once you implement this code, you should notice power-ups spawning occasionally when you destroy a block, which will look like the following figure:

Remember that if you get stuck, you can always check the code provided at the end of the article.

Power-Ups: Collision

Now you need to actually allow the player to pick up power-ups. To do this, you want to check whether the bounding rectangle of the paddle intersects with the bounding rectangle of a power-up. If it does, you grant that power-up capability and mark it for removal from the world.

MonoGame has a Rectangle struct you can use for this purpose. First, in GameObject add a property called BoundingRect that returns the Rectangle bounds of the object.

The Rectangle constructor takes four parameters: the x value of the top-left corner, the y value of the top-left corner, the width, and the height.

In any event, this BoundingRect property should return a newly constructed Rectangle in the get function.

Now that you have this property, you can add a new CheckForPowerups function in Game1 that checks for collision with the power-ups. You should call this function before the call to RemovePowerUps.

In CheckForPowerups, you first need to get the BoundingRect for the paddle. Next, loop through the power-up list and grab the BoundingRect for each power-up.

To check whether one Rectangle intersects with another, there's a handy Intersects member function that returns true if the Rectangle intersects with the one you pass in.

So when the paddle intersects with a power-up, have it call an ActivatePowerUp function, which takes in the PowerUp to be activated as a parameter.

In this new ActivatePowerUp function, for now just set the removal flag to true and play the "powerup" sound effect. Once it is working, you can then implement the actual power-ups.

Power-Up: Ball Catch

The first power-up you'll implement is the ball catch. If the player gets this power-up, the ball doesn't bounce off the paddle. Instead, it gets caught and the player can release the ball using the spacebar.

To support this, you need to add a bool to Ball.cs that tracks whether the ball is caught—if it is, you don't want to change the position in Ball.Update.

Next, you need to add code in Game1 that tracks whether the ball catch power-up is active. If it is, when the ball collides with the paddle, set the caught bool on the ball to true.

If the player presses the spacebar while the power-up is active, release the ball (you could also do this check in Ball.cs). Don't forget that this power-up should be disabled in LoseLife.

You also will want to move the ball/paddle collision counter from Game1.cs into Ball.cs. This way, you can decrement the counter only if the ball isn't already caught (and the counter is > 0, of course). This change also will be necessary to support multi-ball.

There's one last thing you need to do, If you move the paddle while a ball is caught, you need to also move the ball. One way to handle this is to save the X position of the paddle before you call paddle.Update on it and then get the X position after paddle.Update. Apply this difference to the ball's position if it is caught.

I also suggest making a slight improvement to the catch behavior. Set the direction of the ball when it's caught to be either (-0.707f, -0.707f) or (0.707f, -0.707f), depending on whether it was caught on the left or right half of the paddle. This way, players know which way the ball will travel when they release it.

Power-Up: Paddle Size

This power-up is the easiest to implement. All you have to do when it's activated is to change the paddle's texture to paddle_long. In LoseLife, change the texture back to the regular paddle. Just add a member function to Paddle that can swap the correct texture in.

As long as you made all the paddle-related logic relative to width/height, you don't have to change anything else.

Power-Up: Multi-Ball

When the multi-ball power-up is activated, you want to spawn a new ball at the current location of the paddle. To do this, you have to change some of the code in Game1.cs, which currently is designed for only one ball.

First, create a list of balls, much as you did for the blocks/power-ups. Next, make a SpawnBall function that creates a ball based on an offset from the paddle position and adds this ball to the list.

Change Game1.Update/Game1.Draw to loop through all the balls in the list.

You also need to change the CheckForCollisions function so that it takes in a particular ball as a parameter and call the function on each ball during Update.

Because there can now be more than one ball, you don't want to automatically call LoseLife if any particular ball goes off the screen. Instead, mark the ball for removal and then later remove it in a RemoveBalls function, which you should call after you've looped through all the balls in Game1.Update.

If you end up with zero balls in the list, you should then call LoseLife and spawn a new ball.

Once you implement it, you'll be able to have multiple balls up at once, as shown in the following figure:

After adding all these power-ups, the game is definitely a lot more dynamic. However, it's still boring that there isn't a score, lives, or more than one level. You'll add support for these features in the fourth and final article in this tutorial series.

  • + Share This
  • 🔖 Save To Your Account

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