adding an image to a monogame game - tomkleen.comtomkleen.com/csci202/notes/010-images.docx  ·...

15
Content: Images Content refers to the images, sounds, and text that are used in a game. We will now look at how to add images to our games. Images in Monogame are called sprites and the data type that is used to hold an image is the Texture2D data type. The process for using an image in a Monogame program is: 1 Create the image. Use a program like Paint.NET. Save it as a png file (not a jpeg ). 2 Add the image to the program's content. 3 Declare a Texture2D variable to hold the image. 4 Declare a Rectangle variable to position and size the image on the screen. 5 Load the image into the Texture2D variable in the LoadContent method. 6 Draw the image in the Draw method using the spriteBatch.Draw method. Adding an image to a Monogame game Before we can add an image to our game, we need to find an image. Like this: To edit the image: 1 Right-click on it and click on Copy to copy it to the clipboard. 2 Open Paint.NET. 3 Press Ctrl+v to paste the picture into Paint.Net. 4 Use the Rectangle Select tool to select just the flying saucer. 5 Use the Move Selection tool to position the selection as it is below. You want to go right up to the edges of the flying saucer on all four sides. 7/6/2022 document.docx Page 1 of 15

Upload: lamxuyen

Post on 04-Jan-2019

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Adding an image to a Monogame game - tomkleen.comtomkleen.com/CSCI202/Notes/010-Images.docx  · Web viewUFO and save the file as a PNG file, not a JPEG. Adding content to your game

Content: ImagesContent refers to the images, sounds, and text that are used in a game. We will now look at how to add images to our games. Images in Monogame are called sprites and the data type that is used to hold an image is the Texture2D data type. The process for using an image in a Monogame program is:

1 Create the image. Use a program like Paint.NET. Save it as a png file (not a jpeg).2 Add the image to the program's content.3 Declare a Texture2D variable to hold the image.4 Declare a Rectangle variable to position and size the image on the screen.5 Load the image into the Texture2D variable in the LoadContent method.6 Draw the image in the Draw method using the spriteBatch.Draw method.

Adding an image to a Monogame gameBefore we can add an image to our game, we need to find an image. Like this:

To edit the image:

1 Right-click on it and click on Copy to copy it to the clipboard. 2 Open Paint.NET. 3 Press Ctrl+v to paste the picture into Paint.Net.4 Use the Rectangle Select tool to select just the flying saucer. 5 Use the Move Selection tool to position the selection as it is below. You want

to go right up to the edges of the flying saucer on all four sides.

5/13/2023 document.docx Page 1 of 13

Page 2: Adding an image to a Monogame game - tomkleen.comtomkleen.com/CSCI202/Notes/010-Images.docx  · Web viewUFO and save the file as a PNG file, not a JPEG. Adding content to your game

6 Use the Crop tool to crop it so it looks like the one below.

7. Our picture is currently ugly. The flying saucer is carrying around its blue background. We need to get rid of the background by making it transparent. Use

the Magic Wand tool to select the area around the flying saucer. The magic wand tool selects areas that are similar in color. You will have to reduce the tolerance to around 25%. It should look something like this (with a dancing line around the blue areas):

8. Press the Delete key. Do this for all of the background regions. Transparent regions will appear as a gray and white checkerboard. Save your file when you are done.

9. Name the file UFO and save the file as a PNG file, not a JPEG.

Adding content to your gameCreate a new C# Monogame program called SpriteDemo. Images are content, and they need to be loaded in the Content area of your project. Add the image file to a Monogame program by doing the following:

1. Open the Content folder in the Solution Explorer. Right-click on the Content.mgcb file.

2. The Open With dialog box will open. Scroll down to Monogame Pipeline and click on it. If it is not the default, click on the Set as Default button. Click on the OK button.

5/13/2023 document.docx Page 2 of 13

Page 3: Adding an image to a Monogame game - tomkleen.comtomkleen.com/CSCI202/Notes/010-Images.docx  · Web viewUFO and save the file as a PNG file, not a JPEG. Adding content to your game

3. The MonoGame Pipeline program will open:

4. From the toolbar, click on Add Existing Item…

5. Navigate to the image you want to add, click on it, then click on the Open button.

5/13/2023 document.docx Page 3 of 13

Page 4: Adding an image to a Monogame game - tomkleen.comtomkleen.com/CSCI202/Notes/010-Images.docx  · Web viewUFO and save the file as a PNG file, not a JPEG. Adding content to your game

6. When the Add File dialog box appears, choose Copy the file to the directory and click on the OK button.

7. From the menu, click on Build | Build. Or, you can click on the Build button on the toolbar (below). If you are asked if you want to save the project first, click on Yes.

8. Wait until the Build 1 Succeeded message to appear:

5/13/2023 document.docx Page 4 of 13

Page 5: Adding an image to a Monogame game - tomkleen.comtomkleen.com/CSCI202/Notes/010-Images.docx  · Web viewUFO and save the file as a PNG file, not a JPEG. Adding content to your game

9. Close the Monogame Pipeline program by clicking on File | Exit.10. In Visual Studio, right-click on the Content folder. From the popup menus, first choose

Add, then click on Existing Item…

11. The Add Existing Item dialog box will open. Open the Content folder. Your sprite file will not appear until you move to the File Type box, click on the down-arrow, and then click on All Files (*.*). The sprite file will appear. Click on it.

5/13/2023 document.docx Page 5 of 13

Page 6: Adding an image to a Monogame game - tomkleen.comtomkleen.com/CSCI202/Notes/010-Images.docx  · Web viewUFO and save the file as a PNG file, not a JPEG. Adding content to your game

12. Locate the Sprite file and click on it to select it. Click on the Add button. You have now added the sprite image to your project.

Loading Image ContentTwo-dimensional images are called textures in Monogame and their data type is Texture2D.

Once the image has been added to our project, we must do two things: (1) Add a Texture2D variable to hold the image, and (2) When the program begins to run, load the image into the Texture2D variable with a

command in the LoadContent method.To declare a Texture2D variable, add the following code to the declaration area of the program:

Texture2D ufoTexture;

Note that Texture2D appears in light blue, meaning that it is a pre-defined data type. The variable name UFOTexture can be anything as long as it follows the syntax rules of C# for creating an identifier. However, your program will be easier to read if you (1) use a name that describes the image, and (2) add the word "Texture" to the end of the name.After declaring a Texture2D variable to hold the image data, the next step is to load the image data into the variable. This is done in the LoadContent method, the same method that was used to load fonts. The code looks like this:

ufoTexture = Content.Load<Texture2D>("UFO");

The data type, in this case Texture2D, goes between the angle brackets (<>), and the name that you assigned to the image when you created it goes between the quotation marks

5/13/2023 document.docx Page 6 of 13

Page 7: Adding an image to a Monogame game - tomkleen.comtomkleen.com/CSCI202/Notes/010-Images.docx  · Web viewUFO and save the file as a PNG file, not a JPEG. Adding content to your game

(without the file extension). If you named your image something other than UFO.png, then you will have to replace UFO with your file name.

Drawing Images using the SpriteBatchNow that we have a Texture2D variable and we have loaded it with an actual image, we can use it to draw the image on the screen. Images are drawn in the Draw method. Just as with fonts, the image must be drawn on the screen between the spriteBatch.Begin() method and the spriteBatch.End() method.

Drawing ImagesImages are drawn on the screen with the spriteBatch.Draw method (not the DrawString method). To draw an image on the screen, the following information is needed:

1. The image to use.2. The location to draw the image.3. The size to draw the image.4. The color (tint) of the image.

The image must be a Texture2D variable. The location and size are combined in a Rectangle variable. And the color must be a Color.

Drawing images: RectanglesWhen drawing text on the screen, the DrawString method is used, and all that is needed to determine where to draw the text is a Vector2 that specifies the upper-left corner of the text location on the screen. However, when drawing a Texture2D on the screen, we are required to specify a Rectangle (a built-in data type) that the image will appear in. If the rectangle has the same aspect ratio (ratio of the height to the width) as the image, the image will not be distorted. However, if the rectangle has a different aspect ratio from the image, the image will be distorted. When drawing an image on the screen, the spriteBatch.Draw method is used. The spriteBatch.Draw method has several variations; we will use the simplest one. The simplest version of the Draw method requires the following arguments:

(1) The texture to be drawn.(2) A rectangle in which to draw the texture. This allows us to scale the image.(3) The color to use to tint the image. If Color.White is used, then no tinting is done to

the image at all.Monogame provides a Rectangle data type which is used to represent a rectangle. A rectangle is specified by providing four numbers (all of type int):

(1) The X coordinate of its upper-left corner.(2) The Y coordinate of its upper-left corner.(3) The width of the rectangle.(4) The height of the rectangle.

5/13/2023 document.docx Page 7 of 13

Page 8: Adding an image to a Monogame game - tomkleen.comtomkleen.com/CSCI202/Notes/010-Images.docx  · Web viewUFO and save the file as a PNG file, not a JPEG. Adding content to your game

Rectangles are used in Monogame to specify regions on the screen. Since all screen regions are measured in pixels, and pixels can only be integer values, all four of the numbers that are used to specify a rectangle are of type int (integer). Here are the fields that are associated with a rectangle:

Before we declare our image rectangle, we will also use a rectangle to keep track of the screen dimensions, so also add this to the declaration area of the program:

Rectangle screenRectangle;

Initialize these variables in the Initialize method:screenRectangle.X = 0;screenRectangle.Y = 0;screenRectangle.Width = 800;screenRectangle.Height = 480;

A shorter way to do this is:screenRectangle = new Rectangle(0, 0, 800, 480);

Before drawing an image on the screen, we need to create a Rectangle to specify where to draw the image and how big it should be. To declare a UFO Rectangle, add the following to the variable declaration area of your program:

Rectangle ufoRectangle;

Remember that declaring a variable only sets aside memory for the variable. It does not initialize the variable. To initialize a Rectangle, we must assign values to all four of its components. We might expect to do this in the Initialize method, but we are going to do it in the LoadContent method. Add the following to your LoadContent method:

5/13/2023 document.docx Page 8 of 13

Page 9: Adding an image to a Monogame game - tomkleen.comtomkleen.com/CSCI202/Notes/010-Images.docx  · Web viewUFO and save the file as a PNG file, not a JPEG. Adding content to your game

ufoTexture = Content.Load<Texture2D>("UFO");ufoRectangle.X = screenRectangle.Width / 2;ufoRectangle.Y = screenRectangle.Height / 2;ufoRectangle.Width = 120;ufoRectangle.Height = 40;

If we are working with a screen that is 800x480, then these instructions will position the upper-left corner of the rectangle at location (400, 240), which is the middle of the screen. And they set the width to 120 and the height to 40, defining a rectangle whose corners are (400, 240), (520, 240), (400, 280), (520, 280). Like this:

At this point, we have only defined the rectangle; we have not used it to draw anything yet. To draw the picture of the flying saucer, add the following commands to your Draw method:

GraphicsDevice.Clear(Color.CornflowerBlue);

spriteBatch.Begin();spriteBatch.Draw(ufoTexture, ufoRectangle, Color.White);spriteBatch.End();

base.Draw(gameTime);

Note that when you begin to write the Draw command, the following appears:

5/13/2023 document.docx Page 9 of 13

Page 10: Adding an image to a Monogame game - tomkleen.comtomkleen.com/CSCI202/Notes/010-Images.docx  · Web viewUFO and save the file as a PNG file, not a JPEG. Adding content to your game

This tells you that there are actually 8 different versions of the Draw method, and that we are using the first one (1 of 8). The argument list for this version of the Draw method requires that the first argument be of type Texture2D, that the second argument be of type Rectangle, and that the final argument be of type Color.Run the program. You should get the following. NOTE: Since we made the area around the flying saucer transparent, you will not see the dark blue around the saucer, but the dark blue represents the true location of the saucer on the screen.

When an image is drawn in a rectangle on the screen, the image will fill the entire region specified by the rectangle. If the rectangle size is exactly the same as the image size, then the image will appear on the screen exactly as it would appear in any other program. If the rectangle size is larger than the image but the aspect ratio of the rectangle is the same as the aspect ratio of the image, the image will be larger but it will not be distorted. Depending on how much the picture is enlarged, the quality if the image may be degraded.If the aspect ratio of the rectangle is different from the aspect ratio of the image, then the image will be stretched to fill up the rectangle and the image will be distorted.

5/13/2023 document.docx Page 10 of 13

Page 11: Adding an image to a Monogame game - tomkleen.comtomkleen.com/CSCI202/Notes/010-Images.docx  · Web viewUFO and save the file as a PNG file, not a JPEG. Adding content to your game

Try changing the rectangle's width and height and see what happens. Here are some things to try:

Make the flying saucer twice as big. ufoRectangle.Width = 240; ufoRectangle.Height = 80;

Make the flying saucer half as big. ufoRectangle.Width = 60; ufoRectangle.Height = 20;

Set the rectangle's width to 200 and its height to 100. ufoRectangle.Width = 200; ufoRectangle.Height = 100;

Set the rectangle's width to 100 and its height to 200. ufoRectangle.Width = 100; ufoRectangle.Height = 200;

Moving images on the screenImages can be moved around, just like we moved text around earlier. All we need to do is change the image's location by changing its X and Y coordinates. Changes are usually done in the Update method. Let's move the saucer to the top-left corner of the screen. Add the following to the Initialize method:

ufoRectangle.Width = 0; ufoRectangle.Height = 0;

The above code doesn't work! It doesn't work because we set the wrong values to 0. We need to leave the Width and Height alone and change the X and Y:

ufoRectangle.X = 0; ufoRectangle.Y = 0; ufoRectangle.Width = 120; ufoRectangle.Height = 40;

Add the following instruction to the Update method. You can also delete the if statement: if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)

this.Exit();

ufoRectangle.X++;

base.Update(gameTime);

This will cause the rectangle's location to be moved one pixel to the right on every tick of the clock. Note that no changes need to be made to the Draw method. The Draw method simply draws the image at the location that is specified by the Rectangle argument. Try it.

5/13/2023 document.docx Page 11 of 13

Page 12: Adding an image to a Monogame game - tomkleen.comtomkleen.com/CSCI202/Notes/010-Images.docx  · Web viewUFO and save the file as a PNG file, not a JPEG. Adding content to your game

Now comment out the statement to increment the X coordinate:// ufoRectangle.X++;

and add this: ufoRectangle.Y++;

Run the program. This will cause the image's Y location to be incremented every 1/60th of a second. The image will move one pixel down every 1/60th of a second. Since it is starting at Y location 240, after about 4 seconds, the image will have moved 240 pixels down (to location 480) and it will disappear off the bottom of the screen. The Y component of the ufoRectangle variable will continue to be incremented, but since it refers to locations that are not on the screen, nothing will be displayed.Now go back to the Update method and uncomment the statement that increments the X coordinate:

ufoRectangle.X++;

ufoRectangle.Y++;

Run the program. Now we are incrementing both the X and the Y coordinates, so the text should move down and to the right at the same time. When the Y component of the vector reaches 480, (after about 4 seconds) the text will disappear off of the bottom of the screen, never to reappear again.

Controlling the image with the left thumbstickLet's allow the user to move the flying saucer around on the screen using the thumbstick.Add a GamePadState variable:GamePadState pad1;

Read the gamepad on every tick of the clock (so it must go in the Update method):pad1 = GamePad.GetState(PlayerIndex.One);

Respond to movements of the thumbstick. NOTE that if we leave the instructions in to increment X and Y, we will be undoing any instructionsif (pad1.ThumbSticks.Left.X < 0) ufoRectangle.X--;if (pad1.ThumbSticks.Left.X > 0) ufoRectangle.X++;if (pad1.ThumbSticks.Left.Y < 0) ufoRectangle.Y++;if (pad1.ThumbSticks.Left.Y > 0) ufoRectangle.Y--;

This only allows us to move the flying saucer by 1 pixel per tick. If we want to move faster, we can add more than one. The best way to do this is add two more speed variables:int Xspeed = 2, Yspeed = 2;

5/13/2023 document.docx Page 12 of 13

Page 13: Adding an image to a Monogame game - tomkleen.comtomkleen.com/CSCI202/Notes/010-Images.docx  · Web viewUFO and save the file as a PNG file, not a JPEG. Adding content to your game

This will require changing the four statements that add 1 or subtract 1 from the rectangle's X and Y values. Like this:if (pad1.ThumbSticks.Left.X < 0) ufoRectangle.X -= Xspeed;if (pad1.ThumbSticks.Left.X > 0) ufoRectangle.X += Xspeed;if (pad1.ThumbSticks.Left.Y < 0) ufoRectangle.Y += Yspeed;if (pad1.ThumbSticks.Left.Y > 0) ufoRectangle.Y -= Yspeed;

Note that sometimes we use += (add to) and other times we use -= (subtract from).

Keeping an image on the screenTo keep the image on the screen, on each tick of the clock, we must check to see if the image has moved off one of the edges of the screen. To see if it has moved off the left edge:if (ufoRectangle.X < screenRectangle.X) ufoRectangle.X = screenRectangle.X;

To see if it has moved off the top edge:if (ufoRectangle.Y < screenRectangle.Y) ufoRectangle.Y = screenRectangle.Y;

To see if it has moved off the right edge:if (ufoRectangle.Right > screenRectangle.Right) ufoRectangle.X = screenRectangle.Right – ufoRectangle.Width;

To see if it has moved off the bottom edge:if (ufoRectangle.Bottom > screenRectangle.Bottom) ufoRectangle.Y = screenRectangle.Bottom – ufoRectangle.Height;

Note that in all cases, we use > or <. We do not check to see if one of the ufoRectangle's value is equal to the corresponding screenRectangle's value. There is a good reason for this. What if the image is moving in increments of 2 or 3 instead of 1? It is possible that the X value will never be exactly 0 or exactly 800. And it is possible that the Y value will never be 0 or 480. But if we are moving left, the X value will eventually become less than 0. And if we are moving right, the X value will eventually become greater than 800. The same is true for Y. It will eventually become less than 0 or greater than 480.

So we have written our if statement defensively—protecting our program from failing if certain changes are made.

5/13/2023 document.docx Page 13 of 13