XNA Programming: Simple Moving Sprites

The main idea behind moving images is making use the the Update() method. this method is ran every time the game creates a frame (ex. if a game is 60 fps, the method is ran 60 times in one second). All you have to do is draw the sprite to the screen then set up the the update algorithm. One thing to note is when you are drawing out the sprite, you have to create a Class-Level variable for the sprite’s position. For example let’s create a a Class-Level Vector2 variable named position.

Here is a spriteBatch() set up of an example sprite you would like to move (along with the intellisense bar:

 spriteBatch.Draw(yourImage, position, //instead of a local Vector2
 //variable, put class level variable name
 null, //rectangle?
 Color.White, //tint
 0, //rotation
 Vector2.Zero, //origin
 1, //image scale
 0); //layer (depth)


After I declared my variable and drawn the image to the screen, I’ll update it, by putting this algorithm into the Update() method:

 position.X += speed; //oh yea, create a Class-Level float variable
 //and give it a value (non null)
 if (position.X = Window.Clientbounds.Width || position.X 0)
 speed *= –1; 

Line by line this is what the algorithm does, soon as the Update method is started, the Class-Level Vector variable is moved over to the Right by the amount you declared for speed, say my speed = 2.0f, the position of the image you created will be moved over to the right by 2 units for every frame the Update() method calls.

Next line checks whether the position of the image goes beyond the size of the window you’re game is running in OR (||) if the position of the image somehow becomes less than 0 (remember 0 is where the position started, you don’t want the image going beyond that).

Final line, only executes when the previous line is true, all the third line does is reverse the direction of the moving image.

NOTE: This is just how you move the image left to right, you can also move it top to bottom by changing all of the Y values.

Please consider leaving a comment or subscribing to the feed on FeedBurner or add this link (http://mastrgamr.net/feed/) to your feed reader, like the Flipboard app or Google Reader ;)
  • http://www.guildwars2movies.com/categories Malcom Crogan

    Cheers mate, do you happen to have a tweeter i can follow up? really interested.cya

  • http://www.bestotools.com Backlink Software

    Heya admin. I have a simple request. I was just googleing for some info on this topic you wrote and found this post. Some really awesome stuff you got here, can I please share this post on my new website I am currently workin on? It would be great:). I will check back again later to see how you responded. Thank you, Nina Scott .

  • @mastrgamr

    I keep this blog updated ever so seldom, It’s open for anyone to use/learn from for any reason. All I ask is if anyone puts this on a website just provide a link back to the blog. Twitter: @mastrgamr (seldom updated as well)