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 spriteEffects.None, 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.