# How do I make the viewport move?

I'm working with a game in C# XNA and I want to draw a texture and a position in the middle of the screen. The thing is that I want the viewport to move around and not the player. So for example: If I push right I want the viewport to move right and keep the player in the middle of the screen.

Since GraphicsDevice.Viewport.X and Y are not variables, I have no idea how to do this.

• You want the view port to move but not the avatar. If you pushed right and the view port moved right, the avatar would have to move if you wanted them to stay in the middle of the screen. – MichaelHouse Apr 17 '12 at 21:36

Now I know how to do it :)

In SpriteBatch.Begin() you type:

spriteBatch.Begin(SpriteSortMode.Texture,
null,null,null,null,null,
Matrix.CreateTranslation(X,Y,0));


Since it is a 2D game I'm working on the Z axis is 0.

X and Y are where you want your camera to be, so for my example I can type:

Player_position.X - drawOffSet
Player_position.Y - drawOffSet


But thanks for the help anyway

• So moving the viewport wasn't your problem to begin with, you just wanted to move the view within the screen? If you'd just asked that, you'd have gotten an answer the same day since that's basic stuff! Instead you were asking to move the Viewport object, which isn't nearly as basic. The lesson here is: when you have no idea how to do something, don't assume it must be done in this particular way and then ask how to do that particular thing - just ask about the original fundamental thing you want to do. – doppelgreener Apr 20 '12 at 23:57
• ok sorry, i just assumed that the viewport was the camera. I have just worked with Xna for like a half year. But i will keep in mind what you said in the future :) – Eric Nilsson Apr 24 '12 at 16:53
• For monogame users: you can use spriteBatch.Begin(transformMatrix: Matrix.CreateTranslation(x, y, 0)); – trinalbadger587 May 6 '18 at 12:49

if you want to move your viewport you only have to do:

GraphicsDevice.Viewport = new Viewport(X,Y,WIDTH, HEIGHT);


but I'm not sure that it is what you need... usually is used to work with a camera, so the viewport is fixed and you change the camera... like if you were watching tv...

the tv, (your viewport), is fixed..., but the camera is what you moves to show other parts of the film's world.

the best way would be to integrate a camera class there are many tutorials for that

i assume you will be using it for a 2d game...so :