XNA Game Studio 4.0 Keyboard and Mouse Controls + more on Animated Sprites.

Slides:



Advertisements
Similar presentations
2000 Prentice Hall, Inc. All rights reserved. 1 Outline 3.1Introduction 3.2Game Loop Components 3.3How to Implement in C# 3.4Adding Image to XNA Project.
Advertisements

Sprites, User Input, and Collision COSC 315 Fall 2014 Bridget M. Blodgett.
RAPTOR Syntax and Semantics By Lt Col Schorsch
Constructor and New Fields // Don't synch draw() with vertical retrace of monitor graphics.SynchronizeWithVerticalRetrace = false; IsFixedTimeStep = true;
 Variables  What are they?  Declaring and initializing variables  Common uses for variables  Variables you get “for free” in Processing ▪ Aka: Built-in.
11 Reaction Timer Game Session 8.1. Session Overview  Find out how an XNA program can measure the passage of time and trigger events at certain points.
COMPUTER PROGRAMMING 2 Chapter 7 Sound. Objectives Find out how to prepare sounds for inclusion in Microsoft XNA projects. Incorporate sounds into XNA.
2D Graphics in XNA Game Studio Express (Modeling a Class in UML) Game Design Experience Professor Jim Whitehead February 5, 2008 Creative Commons Attribution.
IAT 800 Lab 1: Loops, Animation, and Simple User Interaction.
Input from Controller and Keyboard in XNA Game Studio Express Game Design Experience Professor Jim Whitehead February 12, 2008 Creative Commons Attribution.
Creating a Hand-Drawn Animated Sprite. Sketch and Scan Create the initial image of your animated character by sketching in (possibly blue) pencil. Outline.
Finishing 2D COSC 315 Fall 2014 Bridget M. Blodgett.
Review Blocks of code {.. A bunch of ‘statements’; } Structured programming Learning Processing: Slides by Don Smith 1.
Display 480x800 QVGA 320x480 HVGA Capacitive touch 4 or more contact points Camera 5 mega pixels or more Dedicated camera button Hardware buttons.
Computer Science – Game DesignUC Santa Cruz CMPS 20: Game Design Experience January 14, 2010 Arnav Jhala.
CHAPTER 4 Images XNA Game Studio 4.0. Objectives Find out how the Content Manager lets you add pictures to Microsoft XNA games. Discover how pictures.
Rob Miles Microsoft MVP University of Hull Fun Programming with Visual Studio.
COMPUTER PROGRAMMING 2 Timers. Game Idea: Mob Reaction Timer Use a timer variable to keep track of time and a variable for each player to measure the.
Getting Started. XNA Game Studio 4.0 To download XNA Game Studio 4.0 itself, go to XNA Game.
Using Namepsaces  This section lists the namespaces that the application will be using frequently. Saves the programmer from specifying a fully qualified.
Developing the Game User Interface (UI) Lesson 5.
1 Useful Tools for Making Video Games Part V An overview of.
11 Adding Sounds Session 7.1. Session Overview  Find out how to capture and manipulate sound on a Windows PC  Show how sound is managed as an item of.
User Input and Collisions COSC 315 Fall 2014 Bridget M. Blodgett.
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 7 The Game Loop and Animation Starting Out with Games & Graphics.
11 Using the Keyboard Session Session Overview  Introduce the keyboard device  Show how keys on a keyboard can be represented by enumerated types.
Rob Miles. Creating a Working MoodLight We know that colours in XNA are stored as values which represent the amount of red, blue, green and transparency.
CHAPTER 10 Using C# Methods to Solve Problem XNA Game Studio 4.0.
11 Adding Tomato Targets Session Session Overview  We now have a game which lets a player bounce a piece of cheese on a bread bat  Now we have.
XNA An Introduction. What XNA is… Microsoft® XNA™ is composed of industry- leading software, services, resources, and communities focused on enabling.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Object Oriented Design COSC 315 Fall 2014 Bridget M. Blodgett.
11 Making a Sprite Session 4.2. Session Overview  Describe the principle of a game sprite, and see how to create a sprite in an XNA game  Learn more.
Sprites, User Input, and Collision COSC 315 Fall 2014 Bridget M. Blodgett.
CIS 3.5 Lecture 2.2 More programming with "Processing"
Variables Art &Technology, 3rd Semester Aalborg University Programming David Meredith
2.3. A RCHITECTURAL D ESIGN I Example approach for game screen management.
Aaron Yuen 1 Outline 9.1Storyboarding & Charting Method for Game Design 9.2Game State in Game Development 9.3Game State Management 9.4GUI Assets for Gameplay.
CHAPTER 3 Getting Player Input XNA Game Studio 4.0.
XNA Basic Displaying Image & Collision Detect. What’s format image that XNA support? XNA support only.bmp.png and.jpg image..PNG have transparent region.
CHAPTER 6 Multiplayer XNA Game Studio 4.0. Objectives Discover how to detect and use individual button-press events in a game. Learn how to create and.
G RAPHICS & I NTERACTIVE P ROGRAMMING Lecture 2 More Programming with Processing.
CHAPTER 2 The Game Loop - Variables, Types, Classes and Objects in XNA XNA Game Studio 4.0.
11 Writing Text Session 5.1. Session Overview  Show how fonts are managed in computers  Discover the difference between bitmap fonts and vector fonts.
Playing with Sprites. XNA Game Lifecycle In the faceBall demo program we bounced a smiley face around the graphical display against a background image.
XNA ● Proprietary Microsoft framework ● C#. Interface.
11 Using the Keyboard in XNA Session 9.1. Session Overview  Discover more detail on how the XNA keyboard is implemented  Find out how to use arrays.
XNA Tutorial 1 For CS134 Lecture. Overview Some of the hard work has already been done for you. If you build and run your game now, the GraphicsDeviceManager.
Rob Miles. Using data in an XNA game program An XNA game program Draw and Update methods that are called to run the game Colours are held in XNA as four.
11 Adding Vibration Effects Session Session Overview  Describe how the vibration feature of the gamepad works  Show how an XNA program can control.
XNA Sound Effects. float volume, pitch, pan; SoundEffect boing1; SoundEffect boing2; boing1 = Content.Load ("boing1"); boing2 = Content.Load ("boing2");
Rob Miles. Creating a Broken MoodLight An XNA game contains game data which is used by the Draw and Update methods – Update updates the game data – Draw.
Consumer Windows Phone Emulator Phone Emulator SamplesDocumentation GuidesCommunity Packaging and Verification Tools Windows Phone Dev Tools AppHub.
Variables. Something to mention… void setup(){ size(200, 200); background(255); smooth(); } void draw() { stroke(0); strokeWeight(abs(mouseX-pmouseX));
2D Graphics CMT3311. This covers... How to make a transparent sprite How to add a sprite to your project and draw it Properties of sprites and how to.
CHAPTER 5 Text XNA Game Studio 4.0. Objectives Discover how text is drawn using Microsoft XNA. Add some font resources to your XNA program. Draw some.
XNA 4.0 Side Scrolling.
Lecture 4 Using SpriteFonts
Week 2 - Monday CS361.
Using and Creating Sprites
Java Programming: Guided Learning with Early Objects
Counted Loops.
Collision Detection.
Animated Sprites.
Side Scrolling Game Development.
Animated image sequences, fonts and image transforms
2.3. Architectural Design I
MTA-4201 Game Programming Chapter 8 : Scrolling Background & Font
Collisions with Static Objects
Presentation transcript:

XNA Game Studio 4.0 Keyboard and Mouse Controls + more on Animated Sprites

KeyboardState keyboardState = Keyboard.GetState( ); if (keyboardState.IsKeyDown(Keys.Left)) spritePosition.X -= 2; if (keyboardState.IsKeyDown(Keys.Right)) spritePosition.X += 2; if (keyboardState.IsKeyDown(Keys.Up)) spritePosition.Y -= 2; if (keyboardState.IsKeyDown(Keys.Down)) spritePosition.Y += 2; Keyboard Control of spritePosition The state of every key on the keyboard is loaded into keyboardState when the Keyboard.GetState( ) method is invoked as shown in the following code sample. This permits the sensing of multiple keys being pressed simultaneously. The functionality of similar code can be evaluated with the demo project whirlygig.zip.

Keys Enumeration A list of standard keyboard member names with a description of which key is being pressed is shown here. Member names for special keys on extended keyboards are available from MSDN /library/microsoft.xna.framework. input.keys.aspx

public class whirlygig : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; Texture2D whirlysprite; Rectangle blit = new Rectangle(0, 0, 79, 79); Vector2 blitorigin; Vector2 whirlygigPosition; int maxX, maxY, minX, minY; float scale; int count; SpriteBatch spriteBatch; int msperframe = 40; int delms = 0; public whirlygig() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } protected override void Initialize() { Viewport view = graphics.GraphicsDevice.Viewport; whirlygigPosition.X = view.Width / 2; whirlygigPosition.Y = view.Height / 2; blitorigin.X = blit.Width / 2; blitorigin.Y = blit.Height / 2; maxX = view.Width - blit.Width / 2; maxY = view.Height - blit.Height / 2; minX = blit.Width / 2; minY = blit.Height / 2; scale = (float)1.0; base.Initialize(); count = 0; } sets minimum number of milliseconds between frames for the sprite animation (can be <= game loop rate of 60 frames/sec). will hold the accumulated time since last blit in the animation sequence was first displayed. whirlygig.zip

protected override void Update(GameTime gameTime) { int rownum, colnum; if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); KeyboardState keyboardState = Keyboard.GetState( ); if (keyboardState.IsKeyDown(Keys.Left)) whirlygigPosition.X -= 2; if (keyboardState.IsKeyDown(Keys.Right)) whirlygigPosition.X += 2; if (keyboardState.IsKeyDown(Keys.Up)) whirlygigPosition.Y -= 2; if (keyboardState.IsKeyDown(Keys.Down)) whirlygigPosition.Y += 2; if (keyboardState.IsKeyDown(Keys.PageUp)) scale += (float)0.05; if (keyboardState.IsKeyDown(Keys.PageDown)) scale -= (float)0.05; if (keyboardState.IsKeyDown(Keys.A)) msperframe += 1; if (msperframe > 100) msperframe = 100; if (keyboardState.IsKeyDown(Keys.Z)) msperframe -= 1; if (msperframe < 15) msperframe = 15; if (whirlygigPosition.X > maxX) whirlygigPosition.X = maxX; if (whirlygigPosition.X < minX) whirlygigPosition.X = minX; if (whirlygigPosition.Y > maxY) whirlygigPosition.Y = maxY; if (whirlygigPosition.Y < minY) whirlygigPosition.Y = minY; if (scale < (float)0.25) scale = (float)0.25; if (scale > (float)1.5) scale = (float)1.5; delms += gameTime.ElapsedGameTime.Milliseconds; if (delms > msperframe) { count += 1; if (count > 47) count = 0; rownum = count / 6; colnum = count % 6; blit.X = colnum * ; blit.Y = rownum * ; delms = 0; } base.Update(gameTime); } uses A and Z to change the animation rate range is limited to between 15 & 100 ms. accumulates the total time since the time the animation frame count was changed when delms > msperframe the animation frame count is incremented and delms is reset to zero (0)

The mouseDemo Project includes a demonstration of how to manage multiple instances of an animated sprite appearing simultaneously. We will create instances of a class called kapow and keep them in a generic list while the animation sequence is being displayed. When a sequence is completed that instance of the class will be removed from the list. List bombs = new List (); GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Vector2 origin = new Vector2(0, 0); Texture2D kablam; SpriteFont font; string bombCount = "0"; Vector2 fontPos = new Vector2(10, 10); MouseState mouse; Vector2 Pos; int delms; int msperframe = 30; int deltxt; int mspertext = 200; bool boom; mouseDemo generic list to hold instances of class kapow contains the spritsheet kablam.bmp a spriteFont available in XNA Game Studio 4.0 will be used to display the generic list count animation milliseconds per frame list count display frame time in milliseconds used to ensure only one kapow instance is generated for each button press

Mouse Controls The XNA demo program mouseDemo.zip includes code for getting and using the mouseState as well as a method for loading and accessing a generic list of animated sprites. Let's deal with the mouse controls first. Include the following in global declarations: We can access the state of the mouse in the Update( ) method in the following manner: Other mouse controls are accessed in a similar manner. (Review options in intellisense) MouseState mouse; Vector2 Pos; mouse = Mouse.GetState(); if (mouse.LeftButton.Equals(ButtonState.Pressed)) { Pos.X = mouse.X; Pos.Y = mouse.Y; // do stuff with mouse state here }

public class kapow { public Vector2 Pos; public Rectangle Blit = new Rectangle(); public int NumRow; public int NumCol; public int Width; public int Height; public int AnimCount; public int AnimTot; public bool AnimDone; public kapow(int x, int y, int numrow, int numcol, int width, int height) { Blit.Width = width / numcol; Blit.Height = height / numrow; Pos.X = x - Blit.Width / 2; Pos.Y = y - Blit.Height / 2; AnimCount = 0; NumRow = numrow; NumCol = numcol; AnimTot = numrow * numcol; Blit.X = 0; Blit.Y = 0; AnimDone = false; } Class for an Animated Sprite Each animated explosion sequence in our demo will need its own position, blit location, and frame counter. We will create instances of this class each time the left mouse button is pressed when the Update( ) method is called. sprite frames are assumed to be in a two-D array in the sprite sheet arranged in numrow rows and numcol columns for a total of numrow x numcol frames.

protected override void Initialize() { base.Initialize(); boom = false; IsMouseVisible = true; delms = 0; deltxt = 0; } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); kablam = Content.Load ("kablam"); font = Content.Load ("SpriteFont1"); } mouseDemo Initialization and Content Loading The sprite sheet kablam.bmp is associated with the project by right-clicking mouseDemoContent and selecting Add - Existing Item. The font SpriteFont1 is chosen by right-clicking mouseDemoContent and selecting Add -> New Item -> Sprite Font

Blit.Width = width / numcol; Blit.Height = height / numrow; Pos.X = x - Blit.Width / 2; Pos.Y = y - Blit.Height / 2; AnimCount = 0; NumRow = numrow; NumCol = numcol; AnimTot = numrow * numcol; Blit.X = 0; Blit.Y = 0; AnimDone = false; foreach (kapow pow in bombs) { pow.AnimCount += 1; if (pow.AnimCount >= pow.AnimTot) pow.AnimDone = true; else { pow.Blit.X = (pow.AnimCount % pow.NumCol) * pow.Blit.Width; pow.Blit.Y = (pow.AnimCount / pow.NumCol) * pow.Blit.Height; } numcol numrow Blitting from the Sprite Sheet kablam.bmp properties defined in Class kapow Example: blit for AnimCount = 15 loop in Update( ) method

mouse = Mouse.GetState(); if (mouse.LeftButton.Equals(ButtonState.Pressed) && boom==false || mouse.RightButton.Equals(ButtonState.Pressed)) { Pos.X = mouse.X; Pos.Y = mouse.Y; bombs.Add(new kapow((int)Pos.X, (int)Pos.Y, 5, 6, 880, 665)); boom = true; } if (mouse.LeftButton.Equals(ButtonState.Released)) boom = false; Mouse Controls When the mouse left-button is pressed one instance of kapow is created at the mouse location and added to the generic list bombs. The value of the Boolean boom is set to true and remains true until the left-button is released. This ensures that only one instance of kapow is created for each left-button press. When the mouse right-button is pressed instances of kapow are created and added to the bombs at the game loop rate (60 /sec). Holding down the right-button while moving the mouse produces an effect similar to that shown next.

delms += gameTime.ElapsedGameTime.Milliseconds; if (delms > msperframe) { foreach (kapow pow in bombs) { pow.AnimCount += 1; if (pow.AnimCount >= pow.AnimTot) pow.AnimDone = true; else { pow.Blit.X = (pow.AnimCount % pow.NumCol) * pow.Blit.Width; pow.Blit.Y = (pow.AnimCount / pow.NumCol) * pow.Blit.Height; } delms = 0; } bombs.RemoveAll(delegate(kapow pow) { return pow.AnimDone; }); Managing Multiple Animated Sprites The generic list bombs may hold many instances of kapow, each displaying a different frame of the animation sequence. Each frame lasts for 30 milliseconds (as set in the demo) and after all frames have been displayed, that instance of kapow is tagged for removal (i.e. Animdone is set to true). The removal of completed instances is done through a delegate bombs.RemoveAll( ) as shown. Attempting to remove items from the list within the foreach loop can result in indexing errors and the removal of the wrong instances of kapow.

protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.MidnightBlue); spriteBatch.Begin(); foreach (kapow pow in bombs) spriteBatch.Draw(kablam, pow.Pos, pow.Blit, Color.White, 0, origin, 1, 0, 0); spriteBatch.DrawString(font, bombCount, fontPos, Color.White); spriteBatch.End(); base.Draw(gameTime); } mouseDemo Draw( ) Method In the draw method the currrent frame (blit region) of each kapow sprite in the list bombs is drawn as part of the spriteBatch actions. The number of kapow sprites in bombs is displayed in the upper left-hand corner of the display screen using the DrawString( ) method. deltxt += gameTime.ElapsedGameTime.Milliseconds; if (deltxt > mspertext) { bombCount = Convert.ToString(bombs.Count); deltxt = 0; } The value of bombcount is updated in the Update( ) method at a rate of once every 200 milliseconds. from Update( ) Method

graphics.IsFullScreen = true; graphics.ApplyChanges(); mouse = Mouse.GetState(); if (mouse.LeftButton.Equals(ButtonState.Pressed) && mouse.RightButton.Equals(ButtonState.Pressed)) this.Exit(); Going Fullscreen Since we are dealing building XNA applications for Windows, we will want the option to display our games in fullscreen mode. in the Initialize( ) method, include the following: in the Update( ) Method, include some way to exit the game, such as: