Home > Articles > Programming > C#

Like this article? We recommend

GameObject Class

Although you could put all the code for the game in Game1.cs, it's not a very robust way to write code for a game. If you did it this way, it would be harder in the long run to add to and maintain the game.

What you'll do is make a base GameObject class and then have any objects in the world (including the paddle, ball, and bricks) derive from this base class. Any functionality that all game objects will need can be placed in this class, which will streamline the code.

Although a simple object model wouldn't be used on a AAA game, in this case, it strikes a balance between robustness and ease to write.

To create a new .cs file in Visual Studio, right-click the project in the Solution Explorer and select Add>New Item. Select Class and name it GameObject.cs. The process will be very similar in the other environments.

At the top of this file, you may notice using statements. These statements are much like #include in C++ or import in Java. You want to add a few more using statements to specify that you're using classes from the XNA package:

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

Next, make the GameObject class "public," which signifies that you want to be able to use the class in other files. To do this, simply add a public in front of class GameObject, like this:

public class GameObject

Next, you need to add some member variables inside the class declaration:

  •   A string, which stores the name of the texture this object uses (protected)
  •   A Texture2D, which is for this game object (protected)
  •   A Game instance, which you'll set when you create a GameObject (protected)
  •   A Vector2 to store the position, which specifies where the center of the object is onscreen (public)

These variable declarations should look like this:

protected string textureName = "";
protected Texture2D texture;
protected Game game;
public Vector2 position = Vector2.Zero;

Recall that protected variables are ones that child classes are allowed to modify. Public variables are ones that anyone can access, and although strict object-oriented programming usually doesn't use public variables, for these articles, it will make things easier to make position public.

In any event, once you have these variables, you then need to add some member functions. First, you need to have a constructor that takes in a Game class as a parameter and sets the game member variable to this parameter:

public GameObject(Game myGame)
{
   game = myGame;
}

Next, make a LoadContent function. This function loads in the texture specified in textureName, provided that the string isn't empty:

public virtual void LoadContent()
{
   if (textureName != "")
   {
      texture = game.Content.Load(textureName);
   }
}

Remember that a virtual function is one that can be overridden by child classes. Right now, you won't be overriding anything, but you will do so later on.

Next, you want to make an Update function that takes a float parameter called deltaTime. This function should also be virtual. I'll discuss what this represents in a little bit.

The function will look like this:

public virtual void Update(float deltaTime)
{
}

Finally, you want a Draw function that draws the texture, provided that it's loaded. In order to draw the texture, this function needs to take in a SpriteBatch as a parameter.

Because the position member variable is relative to the center of the GameObject, but drawing is relative to the top-left corner, you need to subtract width / 2 from the X position and half the height / 2 from the Y position to figure out the draw position, as shown in the following figure:

This leaves you with the following Draw function:

public virtual void Draw(SpriteBatch batch)
{
   if (texture != null)
   {
      Vector2 drawPosition = position;
      drawPosition.X -= texture.Width / 2;
      drawPosition.Y -= texture.Height / 2;
      batch.Draw(texture, drawPosition, Color.White);
   }
}

Paddle

Now that you have a GameObject class, you can make a Paddle class that inherits from it. So make a new class called Paddle.cs, and add the same using statements you added to GameObject.

Next, you want to change the declaration of Paddle so it is public and inherits from GameObject, which looks like this:

public class Paddle : GameObject

You need to make a constructor for Paddle that takes in a Game and passes it to the base GameObject class. You pass this using an initializer list, which you might be familiar with if you've used C++ before.

Inside this constructor, set the textureName variable to "paddle":

public Paddle(Game myGame):
   base(myGame)
{
   textureName = "paddle";
}

You'll add some custom code to Paddle in a little while, but for now leave it as is. Instead, you can create an instance of Paddle in Game1.cs.

First, add a member variable to Game1 of type Paddle (I named the variable paddle). After you load the background in LoadContent, add the following code to initialize the paddle:

paddle = new Paddle(this);
paddle.LoadContent();
paddle.position = new Vector2(512, 740);

This code creates the paddle, loads the texture, and sets the position of the paddle to be vertically centered and near the bottom of the window.

Finally, in the Draw function in Game1, after you draw the background, but before the spriteBatch.End call, add this call to draw the paddle:

paddle.Draw(spriteBatch);

Once this is done, you should end up with a paddle on screen that looks like the following figure:

Moving the Paddle

The final thing to do in this article is add the ability to move the paddle. You want to make it so the left and right arrow keys move the paddle.

To do this, I need to introduce the concept of delta time. Games are typically updated several times per second. Each update is called a frame, so "60 frames per second" means that the game updates 60 times in a second.

Delta time is the time, in seconds, that has elapsed since the last frame. In general, everything that moves in a game should be made a function of delta time, which will make the code much more flexible.

What you want to do in Paddle is override the Update function that you declared in GameObject. Add the following function to Paddle.cs:

public override void Update(float deltaTime)
{
   base.Update(deltaTime);
}

Note that the function calls base.Update, which is the Update function declared in the parent class. Before this base.Update call, check the keyboard to figure out whether the left or right arrow is pressed.

You can get the state of the keyboard by using the following line:

KeyboardState keyState = Keyboard.GetState();

Once you have the KeyboardState, you can then check whether a specific key is down. For the left arrow key, you could use the following code:

if (keyState.IsKeyDown(Keys.Left))

And a similar else if could be added for the right arrow key.

Before you actually move the paddle, though, you should add a public float member variable that stores the speed of the Paddle. This speed should correspond to the number of pixels per second you want the paddle to be able to move. For now, set the speed to 500.

For the actual movement code, you want to change the X component of the position by the pixels per second multiplied by the delta time. For example, to move left, you could do this:

position.X -= speed * deltaTime;

And moving right would be the same, except that it's += instead of -=. By writing the code this way, if you later adjust the speed, you won't have to change the update code.

The final thing you need to do is actually call the paddle's Update function. Go back to Game1.cs and look at Update. Under the TODO, you first need to calculate the value of deltaTime.

You can get this by using the following code:

float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;

Finally, call Update on the paddle and pass in the deltaTime.

When you run the game now, you should be able to move the paddle left and right. (You can also move the paddle off the screen, but you'll fix that in the next article!)

Although you certainly could have gotten this far with fewer lines of code, in the long run putting in the extra time to create the GameObject class will pay off.

This will become readily apparent in Part 2, in which you'll add a ball, bricks, and collision with everything.

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