SlideShare une entreprise Scribd logo
1  sur  24
XNA Game Development.


Exercise 1:

Hello World in XNA.



To write a hello world game, first you need to load font to the content folder.

Right click on the content folder and Add->new item
And select Spite font and rename that as Arial.spritefont

Arial is the name of the font we are going to use.

You can use any font that install in the Windows font folder.




Go to Arial.spritefont file



if you like you can change the size and style by modifing Size and Style tags.



<Size>14</Size>

<Style>Regular</Style>
Now in the Game 1.cs you need to write code to draw a string in the screen.



First create a object form SpriteFont to handle our font.

SpriteFont myfont;




Then in the LoadContent() method you can load the font.



myfont = Content.Load<SpriteFont>("Arial");



then in the Draw() metord you can draw the font in the sceran.




spriteBatch.Begin();          / /start the sprite batch process to draw font




spriteBatch.DrawString(myfont, "Hello world", new Vector2(10.0f, 10.0f),
Color.Black);

  //draw the font in the screan



spriteBatch.End();          //end the sprite batch process




Now you can run the project by pressing F5 or by clicking the run button.
Exercise 2:

Draw 2d image.



First you need to load an image to the content folder.

Right click on the content folder and Add->existing items




And select an image form the hard drive.

It could be .bmp,.png,.jpg ,.dds,.tga
Then create a object form Texture2D to handle the image.

Texture2D mytx;




Then in the LoadContent() method you can load the image.



mytx = Content.Load<Texture2D>("img");



then in the Draw() metord you can draw the image in the sceran.




spriteBatch.Begin();          / /start the sprite batch process to draw font




spriteBatch.Draw(mytx,new Rectangle(100,100,600,400), Color.White);




spriteBatch.End();          //end the sprite batch process




Now you can run the project by pressing F5 or by clicking the run button.
Modify the code for 2d animation.



Also you can create 2d animation to this example using these lines of codes.



First initialize a float variable to the animation.



 float val = 0.0f;



Then in Update() metord increment the value to change the position.



val = val + 0.3f;




Finally in the Draw() metord increment the x y positions of the image.



spriteBatch.Draw(mytx,new Rectangle(100+(int)val,100+(int)val,600,400),
Color.White);




Then after press F5 you are ready to play the animation.
Exercise 3:

Using Keyboard and Mouse in a PC game.



First you need to have an image to represent mouse cursor and another image to show the keyboard
usage.



You can add those files in to the content folder.




In the Game1.cs file initialize these variables.



KeyboardState mykeyboardstate;

//create a keyboardstate                 object to get the state of the keyboard
MouseState mymousesatate;

//get the state of the mouse



 SpriteFont myfont;

//add a sprite font to draw String in the screan




Texture2D mytexture, mytexture2;//creating texture object



float Position = 0.0f;//initializing up down position



float Position2 = 0.0f;//initializing left right position



float mousex = 0.0f;//initilizing mousex position



float mousey = 0.0f;//initializing mousey position




Now in the LoadContent() metord write code for load the assest.

//change the window title
Window.Title = "Using the keyboard+mouse-demo";


myfont = Content.Load<SpriteFont>("Arial");

mytexture = Content.Load<Texture2D>("pic");
mytexture2 = Content.Load<Texture2D>("cursor");




Then in the Update() methord you can chack for keyboard and mouse
inputs.



mykeyboardstate = Keyboard.GetState();//capturing the keybard state



mymousesatate = Mouse.GetState();//capturing mouse state



mousex = (float)mymousesatate.X;//getting the x position of the mouse



mousey = (float)mymousesatate.Y;//getting the y position of the mouse




// Move 400 pixels each second

  float moveFactorPerSecond = 80 *
(float)gameTime.ElapsedRealTime.TotalMilliseconds / 1000.0f;




//chage the position according to the key pressed up,down,left,right



 if (mykeyboardstate.IsKeyDown(Keys.Up))

        Position -= moveFactorPerSecond;



  if (mykeyboardstate.IsKeyDown(Keys.Down))

         Position += moveFactorPerSecond;
if (mykeyboardstate.IsKeyDown(Keys.Left))

            Position2 -= moveFactorPerSecond;




 if (mykeyboardstate.IsKeyDown(Keys.Right))

              Position2 += moveFactorPerSecond;




In the Draw () method you can see the Changes of the inputs by drawing the images.




myspitebatch.Begin();//start process



Vector2 position = new Vector2(200.0f + (int)Position2, 200.0f +
((int)Position));

  //setting position with variables (Position1) and (Position2)

  //those variables change the position of the image according to the
key pressing



 myspitebatch.Draw(mytexture, position, Color.White);//drawing the
image



 myspitebatch.DrawString(myfont, "Use Arrowkeys to move the image &
use mouse to point", new Vector2(10.0f, 10.0f), Color.Gold);//drawing
text on the screan
myspitebatch.Draw(mytexture2, new Vector2(mousex, mousey),
Color.White);

          //drawing the cursor image, acording to the mouse position



 myspitebatch.End();//end process




Now you can run the project by pressing F5 or by clicking the run button




Exercise 4:

Crating a Menu system in a PC game.
For the Game state you need to add some images to show the user inputs



You can add those files in to the content folder.




Then you are able to write a code for create a menu system in a XNA game.



In the Game1.cs file initialize these variables.



KeyboardState mykeyboardstate;

//create a keyboardstate                 object to get the state of the keyboard
MouseState mymousesatate;//get the state of the mouse



SpriteFont myfont;//add spite batch and spite font as explained in
tutorial 01-hello world



Texture2D mytexture, mytexture2;//creating texture object



float Position = 0.0f;//initializing up down position



float Position2 = 0.0f;//initializing left right position



float mousex = 0.0f;//initilizing mousex position



float mousey = 0.0f;//initializing mousey position




Using enum we can define the different game states.Then we set the initial stage as start state.




enum Mygamemode

           {

                 start,

                 game,

                 exit



          }    //define game modes start,game,exit
Mygamemode mygame = Mygamemode.start;//assign start mode as initial
mode




Now in the LoadContent() metord write code for load the assest



Window.Title = "Using menu system";



myspitebatch = new SpriteBatch(graphics.GraphicsDevice);//setting
spite batch for graphic device




 myfont = Content.Load<SpriteFont>("Arial"); //loading font



mytexture = Content.Load<Texture2D>("pic");//loding image



 mytexture2 = Content.Load<Texture2D>("cursor");//loding cursor image




Then in the Update() methord you can chack for keyboard and mouse
inputs.



mykeyboardstate = Keyboard.GetState();//capturing the state



 mymousesatate = Mouse.GetState();//capturing mouse state
mousex = (float)mymousesatate.X;//getting the x position of the mouse



 mousey = (float)mymousesatate.Y;//getting the y position of the mouse




// Move 400 pixels each second



 float moveFactorPerSecond = 80 *

               (float)gameTime.ElapsedRealTime.TotalMilliseconds /
1000.0f;




//chage the position according to the key pressed up,down,left,right



if (mykeyboardstate.IsKeyDown(Keys.Up))

               Position -= moveFactorPerSecond;




if (mykeyboardstate.IsKeyDown(Keys.Down))

               Position += moveFactorPerSecond;



if (mykeyboardstate.IsKeyDown(Keys.Left))

               Position2 -= moveFactorPerSecond;
if (mykeyboardstate.IsKeyDown(Keys.Right))

                      Position2 += moveFactorPerSecond;




In the Draw () method you can see the Changes by drawing the images.




if (mygame == Mygamemode.start) //chack whether you are in the start
mode



  {



 myspitebatch.Begin();




 myspitebatch.DrawString(myfont, "Welcome to the demo ", new
Vector2(30.0f, 30.0f), Color.YellowGreen);



myspitebatch.DrawString(myfont, "Press Enter to continue..... ", new
Vector2(30.0f, 80.0f), Color.YellowGreen);

                      myspitebatch.End();
if (mykeyboardstate.IsKeyDown(Keys.Enter))//chack whather user press
enter key while he/she in the start mode




mygame = Mygamemode.game;   //if(true) assign game mode




 }




if (mygame == Mygamemode.game)//chack whether you are in the game mode



{

              myspitebatch.Begin();//start process




 Vector2 position = new Vector2(200.0f + (int)Position2, 200.0f +
((int)Position));



//setting position with variables (Position1) and (Position2)




  //those variables change the position of the image according to the
key pressing
myspitebatch.Draw(mytexture, position, Color.White);//drawing the
image




  myspitebatch.DrawString(myfont, "Use Arrowkeys to move the image &
use mouse to point", new Vector2(10.0f, 10.0f), Color.Gold);//drawing
text on the screan




myspitebatch.DrawString(myfont, "Use Esc to exit demo", new
Vector2(10.0f, 30.0f), Color.Gold);//drawing text on the screan




 myspitebatch.Draw(mytexture2, new Vector2(mousex, mousey),
Color.White);




//drawing the cursor image, acording to the mouse position

               myspitebatch.End();//end process




 if (mykeyboardstate.IsKeyDown(Keys.Escape))//chack whather user press
escape key while he/she in the start mode
mygame = Mygamemode.exit;      //if(true) assign exit mode




}




 if (mygame == Mygamemode.exit) //chack whether you are in the exit
mode




{   myspitebatch.Begin();




   myspitebatch.DrawString(myfont, "Goodbuy from the demo ", new
Vector2(30.0f, 30.0f), Color.YellowGreen);




 myspitebatch.DrawString(myfont, "Press Q to exit..... ", new
Vector2(30.0f, 80.0f), Color.YellowGreen);




myspitebatch.End();




  if (mykeyboardstate.IsKeyDown(Keys.Q))//chack whather user press
enter key while he/she in the start mode
this.Exit();                     //if(true) assign game mode

}




Now you can run the project by pressing F5 or by clicking the run button.




Exercise 5:
First you need to add Music files (.mp3, .wav) to the content folder in a new XNA project.




In the Game1.cs file initialize these variables.



Song mysong;//initialize the song



SpriteFont myfont;//initialize font



 String val;



 Texture2D mytx;//initialize texture
Now in the LoadContent() metord write code for load the assest



    Window.AllowUserResizing = true;




    //first add new mp3 to a content folder



mysong = Content.Load<Song>("sum41");//load the mp3



myfont = Content.Load<SpriteFont>("Arial");//load the font



mytx = Content.Load<Texture2D>("B");//load the image




    MediaPlayer.Play(mysong);//play the song




Then in the Update() methord you can write this code segment.

//simple text effect



if (gameTime.TotalGameTime.Seconds % 2 == 0)



{

    val = "Playing -sum 41"

 }
else



 {



  val = "";




 }




In the Draw () method you can see the Changes by drawing the images.




spriteBatch.Begin();           //begin spite batch prosess




 spriteBatch.Draw(mytx, new Rectangle(0, 0, Window.ClientBounds.Width,
Window.ClientBounds.Height),

                      Color.White);

//draw image




spriteBatch.DrawString(myfont, val,

                     new Vector2(30.0f, 30.0f), Color.Orange);

//draw the font
spriteBatch.End();//end spite batch process


Now you can run the project by pressing F5 or by clicking the run button.

Contenu connexe

Tendances

Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
Jussi Pohjolainen
 

Tendances (19)

Introduction to Game Programming: Using C# and Unity 3D - Chapter 7 (Preview)
Introduction to Game Programming: Using C# and Unity 3D - Chapter 7 (Preview)Introduction to Game Programming: Using C# and Unity 3D - Chapter 7 (Preview)
Introduction to Game Programming: Using C# and Unity 3D - Chapter 7 (Preview)
 
The Ring programming language version 1.7 book - Part 53 of 196
The Ring programming language version 1.7 book - Part 53 of 196The Ring programming language version 1.7 book - Part 53 of 196
The Ring programming language version 1.7 book - Part 53 of 196
 
Introduction to Game Programming: Using C# and Unity 3D - Chapter 2 (Preview)
Introduction to Game Programming: Using C# and Unity 3D - Chapter 2 (Preview)Introduction to Game Programming: Using C# and Unity 3D - Chapter 2 (Preview)
Introduction to Game Programming: Using C# and Unity 3D - Chapter 2 (Preview)
 
Introduction to Game Programming: Using C# and Unity 3D - Chapter 3 (Preview)
Introduction to Game Programming: Using C# and Unity 3D - Chapter 3 (Preview)Introduction to Game Programming: Using C# and Unity 3D - Chapter 3 (Preview)
Introduction to Game Programming: Using C# and Unity 3D - Chapter 3 (Preview)
 
The Ring programming language version 1.2 book - Part 50 of 84
The Ring programming language version 1.2 book - Part 50 of 84The Ring programming language version 1.2 book - Part 50 of 84
The Ring programming language version 1.2 book - Part 50 of 84
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
The Ring programming language version 1.5.4 book - Part 48 of 185
The Ring programming language version 1.5.4 book - Part 48 of 185The Ring programming language version 1.5.4 book - Part 48 of 185
The Ring programming language version 1.5.4 book - Part 48 of 185
 
The Ring programming language version 1.5.2 book - Part 49 of 181
The Ring programming language version 1.5.2 book - Part 49 of 181The Ring programming language version 1.5.2 book - Part 49 of 181
The Ring programming language version 1.5.2 book - Part 49 of 181
 
The Ring programming language version 1.5.1 book - Part 48 of 180
The Ring programming language version 1.5.1 book - Part 48 of 180The Ring programming language version 1.5.1 book - Part 48 of 180
The Ring programming language version 1.5.1 book - Part 48 of 180
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
The Ring programming language version 1.10 book - Part 70 of 212
The Ring programming language version 1.10 book - Part 70 of 212The Ring programming language version 1.10 book - Part 70 of 212
The Ring programming language version 1.10 book - Part 70 of 212
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 
TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...
TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...
TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...
 
The Ring programming language version 1.9 book - Part 80 of 210
The Ring programming language version 1.9 book - Part 80 of 210The Ring programming language version 1.9 book - Part 80 of 210
The Ring programming language version 1.9 book - Part 80 of 210
 
The Ring programming language version 1.4 book - Part 14 of 30
The Ring programming language version 1.4 book - Part 14 of 30The Ring programming language version 1.4 book - Part 14 of 30
The Ring programming language version 1.4 book - Part 14 of 30
 
The Ring programming language version 1.5.3 book - Part 48 of 184
The Ring programming language version 1.5.3 book - Part 48 of 184The Ring programming language version 1.5.3 book - Part 48 of 184
The Ring programming language version 1.5.3 book - Part 48 of 184
 
HoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial MappingHoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial Mapping
 
The Ring programming language version 1.2 book - Part 36 of 84
The Ring programming language version 1.2 book - Part 36 of 84The Ring programming language version 1.2 book - Part 36 of 84
The Ring programming language version 1.2 book - Part 36 of 84
 
Test Driven Cocos2d
Test Driven Cocos2dTest Driven Cocos2d
Test Driven Cocos2d
 

En vedette

Personal Learning Network
Personal Learning NetworkPersonal Learning Network
Personal Learning Network
samspector93
 
Meridian Terms and Conditions
Meridian Terms and ConditionsMeridian Terms and Conditions
Meridian Terms and Conditions
AeroSvit Airlines
 
Hassinger Chiropractic Clinic
Hassinger Chiropractic ClinicHassinger Chiropractic Clinic
Hassinger Chiropractic Clinic
Keith Hassinger
 
Proyecto Cactus 1°3vesp
Proyecto Cactus 1°3vespProyecto Cactus 1°3vesp
Proyecto Cactus 1°3vesp
guest32ff1ff
 
ממלחמה זעירה למלחמה סדירה
ממלחמה זעירה למלחמה סדירהממלחמה זעירה למלחמה סדירה
ממלחמה זעירה למלחמה סדירה
haimkarel
 
Proposal 0323 (Stan)
Proposal 0323 (Stan)Proposal 0323 (Stan)
Proposal 0323 (Stan)
guest7fe64c
 
Hyves Cbw Mitex Harry Van Wouter
Hyves Cbw Mitex Harry Van WouterHyves Cbw Mitex Harry Van Wouter
Hyves Cbw Mitex Harry Van Wouter
guest2f17d3
 

En vedette (20)

NII
NIINII
NII
 
Personal Learning Network
Personal Learning NetworkPersonal Learning Network
Personal Learning Network
 
Buyuk Taslar
Buyuk  TaslarBuyuk  Taslar
Buyuk Taslar
 
Html
HtmlHtml
Html
 
N Ivanov Market Failure
N Ivanov Market FailureN Ivanov Market Failure
N Ivanov Market Failure
 
Zhang Eye Movement As An Interaction Mechanism For Relevance Feedback In A Co...
Zhang Eye Movement As An Interaction Mechanism For Relevance Feedback In A Co...Zhang Eye Movement As An Interaction Mechanism For Relevance Feedback In A Co...
Zhang Eye Movement As An Interaction Mechanism For Relevance Feedback In A Co...
 
Liang Content Based Image Retrieval Using A Combination Of Visual Features An...
Liang Content Based Image Retrieval Using A Combination Of Visual Features An...Liang Content Based Image Retrieval Using A Combination Of Visual Features An...
Liang Content Based Image Retrieval Using A Combination Of Visual Features An...
 
TDR u Srbiji - pregled poslovanja - press konferencija 13.03.2012
TDR u Srbiji - pregled poslovanja - press konferencija 13.03.2012TDR u Srbiji - pregled poslovanja - press konferencija 13.03.2012
TDR u Srbiji - pregled poslovanja - press konferencija 13.03.2012
 
Meridian Terms and Conditions
Meridian Terms and ConditionsMeridian Terms and Conditions
Meridian Terms and Conditions
 
Madness
MadnessMadness
Madness
 
Hassinger Chiropractic Clinic
Hassinger Chiropractic ClinicHassinger Chiropractic Clinic
Hassinger Chiropractic Clinic
 
Keele Interview
Keele InterviewKeele Interview
Keele Interview
 
Hussain Learning Relevant Eye Movement Feature Spaces Across Users
Hussain Learning Relevant Eye Movement Feature Spaces Across UsersHussain Learning Relevant Eye Movement Feature Spaces Across Users
Hussain Learning Relevant Eye Movement Feature Spaces Across Users
 
NCNG Social Media Webinar 3.24.10
NCNG Social Media Webinar 3.24.10NCNG Social Media Webinar 3.24.10
NCNG Social Media Webinar 3.24.10
 
Proyecto Cactus 1°3vesp
Proyecto Cactus 1°3vespProyecto Cactus 1°3vesp
Proyecto Cactus 1°3vesp
 
ממלחמה זעירה למלחמה סדירה
ממלחמה זעירה למלחמה סדירהממלחמה זעירה למלחמה סדירה
ממלחמה זעירה למלחמה סדירה
 
Proposal 0323 (Stan)
Proposal 0323 (Stan)Proposal 0323 (Stan)
Proposal 0323 (Stan)
 
Hyves Cbw Mitex Harry Van Wouter
Hyves Cbw Mitex Harry Van WouterHyves Cbw Mitex Harry Van Wouter
Hyves Cbw Mitex Harry Van Wouter
 
C:\Documents And Settings\Freddy Kruger\Pulpit\Niedziela Palmowa
C:\Documents And Settings\Freddy Kruger\Pulpit\Niedziela PalmowaC:\Documents And Settings\Freddy Kruger\Pulpit\Niedziela Palmowa
C:\Documents And Settings\Freddy Kruger\Pulpit\Niedziela Palmowa
 
Daugherty Measuring Vergence Over Stereoscopic Video With A Remote Eye Tracker
Daugherty Measuring Vergence Over Stereoscopic Video With A Remote Eye TrackerDaugherty Measuring Vergence Over Stereoscopic Video With A Remote Eye Tracker
Daugherty Measuring Vergence Over Stereoscopic Video With A Remote Eye Tracker
 

Similaire à XNA coding series

import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdfimport java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
venkt12345
 
The following GUI is displayed once the application startsThe sug.pdf
The following GUI is displayed once the application startsThe sug.pdfThe following GUI is displayed once the application startsThe sug.pdf
The following GUI is displayed once the application startsThe sug.pdf
arihantsherwani
 
Chapter 02 sprite and texture
Chapter 02 sprite and textureChapter 02 sprite and texture
Chapter 02 sprite and texture
boybuon205
 
Modify the following source code so that when the mouse is clicked w.pdf
Modify the following source code so that when the mouse is clicked w.pdfModify the following source code so that when the mouse is clicked w.pdf
Modify the following source code so that when the mouse is clicked w.pdf
arorastores
 

Similaire à XNA coding series (20)

Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)
 
Flash auto play image gallery
Flash auto play image galleryFlash auto play image gallery
Flash auto play image gallery
 
School For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsSchool For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine Basics
 
Making Games in JavaScript
Making Games in JavaScriptMaking Games in JavaScript
Making Games in JavaScript
 
Keynote + Next Gen UIs.pptx
Keynote + Next Gen UIs.pptxKeynote + Next Gen UIs.pptx
Keynote + Next Gen UIs.pptx
 
How to make a video game
How to make a video gameHow to make a video game
How to make a video game
 
Introduction to Unity3D and Building your First Game
Introduction to Unity3D and Building your First GameIntroduction to Unity3D and Building your First Game
Introduction to Unity3D and Building your First Game
 
Building your first game in Unity 3d by Sarah Sexton
Building your first game in Unity 3d  by Sarah SextonBuilding your first game in Unity 3d  by Sarah Sexton
Building your first game in Unity 3d by Sarah Sexton
 
98 374 Lesson 05-slides
98 374 Lesson 05-slides98 374 Lesson 05-slides
98 374 Lesson 05-slides
 
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdfimport java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
 
Creating a Facebook Clone - Part XV - Transcript.pdf
Creating a Facebook Clone - Part XV - Transcript.pdfCreating a Facebook Clone - Part XV - Transcript.pdf
Creating a Facebook Clone - Part XV - Transcript.pdf
 
Unity3 d devfest-2014
Unity3 d devfest-2014Unity3 d devfest-2014
Unity3 d devfest-2014
 
Graphical User Components Part 2
Graphical User Components Part 2Graphical User Components Part 2
Graphical User Components Part 2
 
The following GUI is displayed once the application startsThe sug.pdf
The following GUI is displayed once the application startsThe sug.pdfThe following GUI is displayed once the application startsThe sug.pdf
The following GUI is displayed once the application startsThe sug.pdf
 
Writing videogames with titanium appcelerator
Writing videogames with titanium appceleratorWriting videogames with titanium appcelerator
Writing videogames with titanium appcelerator
 
Game age ppt
Game age pptGame age ppt
Game age ppt
 
Chapter 02 sprite and texture
Chapter 02 sprite and textureChapter 02 sprite and texture
Chapter 02 sprite and texture
 
Modify the following source code so that when the mouse is clicked w.pdf
Modify the following source code so that when the mouse is clicked w.pdfModify the following source code so that when the mouse is clicked w.pdf
Modify the following source code so that when the mouse is clicked w.pdf
 
How to Create Custom Shaders in Flutter?
How to Create Custom Shaders in Flutter?How to Create Custom Shaders in Flutter?
How to Create Custom Shaders in Flutter?
 
Creating a Facebook Clone - Part XLI - Transcript.pdf
Creating a Facebook Clone - Part XLI - Transcript.pdfCreating a Facebook Clone - Part XLI - Transcript.pdf
Creating a Facebook Clone - Part XLI - Transcript.pdf
 

Dernier

Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
ssuserdda66b
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Dernier (20)

Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 

XNA coding series

  • 1. XNA Game Development. Exercise 1: Hello World in XNA. To write a hello world game, first you need to load font to the content folder. Right click on the content folder and Add->new item
  • 2. And select Spite font and rename that as Arial.spritefont Arial is the name of the font we are going to use. You can use any font that install in the Windows font folder. Go to Arial.spritefont file if you like you can change the size and style by modifing Size and Style tags. <Size>14</Size> <Style>Regular</Style>
  • 3. Now in the Game 1.cs you need to write code to draw a string in the screen. First create a object form SpriteFont to handle our font. SpriteFont myfont; Then in the LoadContent() method you can load the font. myfont = Content.Load<SpriteFont>("Arial"); then in the Draw() metord you can draw the font in the sceran. spriteBatch.Begin(); / /start the sprite batch process to draw font spriteBatch.DrawString(myfont, "Hello world", new Vector2(10.0f, 10.0f), Color.Black); //draw the font in the screan spriteBatch.End(); //end the sprite batch process Now you can run the project by pressing F5 or by clicking the run button.
  • 4. Exercise 2: Draw 2d image. First you need to load an image to the content folder. Right click on the content folder and Add->existing items And select an image form the hard drive. It could be .bmp,.png,.jpg ,.dds,.tga
  • 5. Then create a object form Texture2D to handle the image. Texture2D mytx; Then in the LoadContent() method you can load the image. mytx = Content.Load<Texture2D>("img"); then in the Draw() metord you can draw the image in the sceran. spriteBatch.Begin(); / /start the sprite batch process to draw font spriteBatch.Draw(mytx,new Rectangle(100,100,600,400), Color.White); spriteBatch.End(); //end the sprite batch process Now you can run the project by pressing F5 or by clicking the run button.
  • 6. Modify the code for 2d animation. Also you can create 2d animation to this example using these lines of codes. First initialize a float variable to the animation. float val = 0.0f; Then in Update() metord increment the value to change the position. val = val + 0.3f; Finally in the Draw() metord increment the x y positions of the image. spriteBatch.Draw(mytx,new Rectangle(100+(int)val,100+(int)val,600,400), Color.White); Then after press F5 you are ready to play the animation.
  • 7. Exercise 3: Using Keyboard and Mouse in a PC game. First you need to have an image to represent mouse cursor and another image to show the keyboard usage. You can add those files in to the content folder. In the Game1.cs file initialize these variables. KeyboardState mykeyboardstate; //create a keyboardstate object to get the state of the keyboard
  • 8. MouseState mymousesatate; //get the state of the mouse SpriteFont myfont; //add a sprite font to draw String in the screan Texture2D mytexture, mytexture2;//creating texture object float Position = 0.0f;//initializing up down position float Position2 = 0.0f;//initializing left right position float mousex = 0.0f;//initilizing mousex position float mousey = 0.0f;//initializing mousey position Now in the LoadContent() metord write code for load the assest. //change the window title Window.Title = "Using the keyboard+mouse-demo"; myfont = Content.Load<SpriteFont>("Arial"); mytexture = Content.Load<Texture2D>("pic");
  • 9. mytexture2 = Content.Load<Texture2D>("cursor"); Then in the Update() methord you can chack for keyboard and mouse inputs. mykeyboardstate = Keyboard.GetState();//capturing the keybard state mymousesatate = Mouse.GetState();//capturing mouse state mousex = (float)mymousesatate.X;//getting the x position of the mouse mousey = (float)mymousesatate.Y;//getting the y position of the mouse // Move 400 pixels each second float moveFactorPerSecond = 80 * (float)gameTime.ElapsedRealTime.TotalMilliseconds / 1000.0f; //chage the position according to the key pressed up,down,left,right if (mykeyboardstate.IsKeyDown(Keys.Up)) Position -= moveFactorPerSecond; if (mykeyboardstate.IsKeyDown(Keys.Down)) Position += moveFactorPerSecond;
  • 10. if (mykeyboardstate.IsKeyDown(Keys.Left)) Position2 -= moveFactorPerSecond; if (mykeyboardstate.IsKeyDown(Keys.Right)) Position2 += moveFactorPerSecond; In the Draw () method you can see the Changes of the inputs by drawing the images. myspitebatch.Begin();//start process Vector2 position = new Vector2(200.0f + (int)Position2, 200.0f + ((int)Position)); //setting position with variables (Position1) and (Position2) //those variables change the position of the image according to the key pressing myspitebatch.Draw(mytexture, position, Color.White);//drawing the image myspitebatch.DrawString(myfont, "Use Arrowkeys to move the image & use mouse to point", new Vector2(10.0f, 10.0f), Color.Gold);//drawing text on the screan
  • 11. myspitebatch.Draw(mytexture2, new Vector2(mousex, mousey), Color.White); //drawing the cursor image, acording to the mouse position myspitebatch.End();//end process Now you can run the project by pressing F5 or by clicking the run button Exercise 4: Crating a Menu system in a PC game.
  • 12. For the Game state you need to add some images to show the user inputs You can add those files in to the content folder. Then you are able to write a code for create a menu system in a XNA game. In the Game1.cs file initialize these variables. KeyboardState mykeyboardstate; //create a keyboardstate object to get the state of the keyboard
  • 13. MouseState mymousesatate;//get the state of the mouse SpriteFont myfont;//add spite batch and spite font as explained in tutorial 01-hello world Texture2D mytexture, mytexture2;//creating texture object float Position = 0.0f;//initializing up down position float Position2 = 0.0f;//initializing left right position float mousex = 0.0f;//initilizing mousex position float mousey = 0.0f;//initializing mousey position Using enum we can define the different game states.Then we set the initial stage as start state. enum Mygamemode { start, game, exit } //define game modes start,game,exit
  • 14. Mygamemode mygame = Mygamemode.start;//assign start mode as initial mode Now in the LoadContent() metord write code for load the assest Window.Title = "Using menu system"; myspitebatch = new SpriteBatch(graphics.GraphicsDevice);//setting spite batch for graphic device myfont = Content.Load<SpriteFont>("Arial"); //loading font mytexture = Content.Load<Texture2D>("pic");//loding image mytexture2 = Content.Load<Texture2D>("cursor");//loding cursor image Then in the Update() methord you can chack for keyboard and mouse inputs. mykeyboardstate = Keyboard.GetState();//capturing the state mymousesatate = Mouse.GetState();//capturing mouse state
  • 15. mousex = (float)mymousesatate.X;//getting the x position of the mouse mousey = (float)mymousesatate.Y;//getting the y position of the mouse // Move 400 pixels each second float moveFactorPerSecond = 80 * (float)gameTime.ElapsedRealTime.TotalMilliseconds / 1000.0f; //chage the position according to the key pressed up,down,left,right if (mykeyboardstate.IsKeyDown(Keys.Up)) Position -= moveFactorPerSecond; if (mykeyboardstate.IsKeyDown(Keys.Down)) Position += moveFactorPerSecond; if (mykeyboardstate.IsKeyDown(Keys.Left)) Position2 -= moveFactorPerSecond;
  • 16. if (mykeyboardstate.IsKeyDown(Keys.Right)) Position2 += moveFactorPerSecond; In the Draw () method you can see the Changes by drawing the images. if (mygame == Mygamemode.start) //chack whether you are in the start mode { myspitebatch.Begin(); myspitebatch.DrawString(myfont, "Welcome to the demo ", new Vector2(30.0f, 30.0f), Color.YellowGreen); myspitebatch.DrawString(myfont, "Press Enter to continue..... ", new Vector2(30.0f, 80.0f), Color.YellowGreen); myspitebatch.End();
  • 17. if (mykeyboardstate.IsKeyDown(Keys.Enter))//chack whather user press enter key while he/she in the start mode mygame = Mygamemode.game; //if(true) assign game mode } if (mygame == Mygamemode.game)//chack whether you are in the game mode { myspitebatch.Begin();//start process Vector2 position = new Vector2(200.0f + (int)Position2, 200.0f + ((int)Position)); //setting position with variables (Position1) and (Position2) //those variables change the position of the image according to the key pressing
  • 18. myspitebatch.Draw(mytexture, position, Color.White);//drawing the image myspitebatch.DrawString(myfont, "Use Arrowkeys to move the image & use mouse to point", new Vector2(10.0f, 10.0f), Color.Gold);//drawing text on the screan myspitebatch.DrawString(myfont, "Use Esc to exit demo", new Vector2(10.0f, 30.0f), Color.Gold);//drawing text on the screan myspitebatch.Draw(mytexture2, new Vector2(mousex, mousey), Color.White); //drawing the cursor image, acording to the mouse position myspitebatch.End();//end process if (mykeyboardstate.IsKeyDown(Keys.Escape))//chack whather user press escape key while he/she in the start mode
  • 19. mygame = Mygamemode.exit; //if(true) assign exit mode } if (mygame == Mygamemode.exit) //chack whether you are in the exit mode { myspitebatch.Begin(); myspitebatch.DrawString(myfont, "Goodbuy from the demo ", new Vector2(30.0f, 30.0f), Color.YellowGreen); myspitebatch.DrawString(myfont, "Press Q to exit..... ", new Vector2(30.0f, 80.0f), Color.YellowGreen); myspitebatch.End(); if (mykeyboardstate.IsKeyDown(Keys.Q))//chack whather user press enter key while he/she in the start mode
  • 20. this.Exit(); //if(true) assign game mode } Now you can run the project by pressing F5 or by clicking the run button. Exercise 5:
  • 21. First you need to add Music files (.mp3, .wav) to the content folder in a new XNA project. In the Game1.cs file initialize these variables. Song mysong;//initialize the song SpriteFont myfont;//initialize font String val; Texture2D mytx;//initialize texture
  • 22. Now in the LoadContent() metord write code for load the assest Window.AllowUserResizing = true; //first add new mp3 to a content folder mysong = Content.Load<Song>("sum41");//load the mp3 myfont = Content.Load<SpriteFont>("Arial");//load the font mytx = Content.Load<Texture2D>("B");//load the image MediaPlayer.Play(mysong);//play the song Then in the Update() methord you can write this code segment. //simple text effect if (gameTime.TotalGameTime.Seconds % 2 == 0) { val = "Playing -sum 41" }
  • 23. else { val = ""; } In the Draw () method you can see the Changes by drawing the images. spriteBatch.Begin(); //begin spite batch prosess spriteBatch.Draw(mytx, new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height), Color.White); //draw image spriteBatch.DrawString(myfont, val, new Vector2(30.0f, 30.0f), Color.Orange); //draw the font
  • 24. spriteBatch.End();//end spite batch process Now you can run the project by pressing F5 or by clicking the run button.