1
\$\begingroup\$

I am trying to get a sprite to position itself at the center of the screen but nothing seems to be working for me. I'm trying

Viewport viewport = graphics.GraphicsDevice.Viewport;
logoPosition = new Vector2((viewport.Width - towerImage.Width) / 2,
                           (viewport.Height - towerImage.Height) / 2);

and

spriteBatch.Draw(towerImage, centre, null, Color.White, 0, baseOrigin, 1.0f, SpriteEffects.None, 0);

This is my first time using XNA and I don't really have a clue what I'm doing.

\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

Unless you pasted your example wrong, you're not even using the logoPosition you calculated when drawing, and you're not showing what the contents of centreand baseOriginare, so it's hard to tell you where the problem is.

But anyway I'd use the position and origin parameters of SpriteBatch.Draw in order to draw the image centered. In two steps, although you could inline:

  1. Calculate the center of the screen and the center of the image:

    Vector2 screenCenter = new Vector2(viewport.Width / 2f, viewport.Height / 2f);
    Vector2 imageCenter = new Vector2(towerImage.Width / 2f, towerImage.Height / 2f);
    
  2. Use the center of the screen as the position and the center of the image as the origin:

                                 // position                          // origin
    spriteBatch.Draw(towerImage, screenCenter, null, Color.White, 0f, imageCenter, 1f, SpriteEffects.None, 0f);
    
\$\endgroup\$
1
\$\begingroup\$

I've never used XNA for a windows phone but I already can tell what your problem is. You aren't following order of operations. Try this:

Viewport viewport = graphics.GraphicsDevice.Viewport;
logoPosition = new Vector2(viewport.Width - towerImage.Width / 2,
                           viewport.Height - towerImage.Height / 2);

You must divide the second height/width before you subtract if from the original. Otherwise it just negates itself and then divides 0 by 2.

\$\endgroup\$
1
  • \$\begingroup\$ You must have misunderstood some part, since what he was doing is essentially the same as viewportSize/2 - imageSize/2 which is correct. In other words, it calculates the center of the screen, and then subtracts half of the size of the image in order to center it there. Also, the thing about the negation would only happen if viewport and towerImage had the same size, which is unlikely, and even in that case, the result is correct (i.e. 0/2 = 0). \$\endgroup\$ May 31, 2012 at 1:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .