Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How do I create a scrolling X and scrolling Y background without weird things happening like the player disappearing or not getting the offset correct?

I have code at

Looks like this:

      var s =;
      var g =;
      var p = game.player.Bounds;
      var v = viewRectangle;

      var x = p.X  0 ? p.X - s.Width/2 :
              v.Right >= 1090 ?  90 :
              p.X > s.Width/2    ? p.X - s.Width/2 :

      var y = //v.Bottom > 
              p.Y > s.Height/2 ? p.Y - s.Height/2:

      var w = s.Width;
      var h = s.Height;

      //view Rectangle
      Offset        = new Vector2(x , y);
      viewRectangle = new Rectangle( x, y ,w, h);

and then:

     //source rectangle
     var x = (int)0;
     var y = (int)0;
     var g =;
     var w = g.Width;
     var h = g.Height;
     var rect =  new Rectangle(x,y,w,h);

      spriteBatch.Draw(  w.boundsTexture 

Before center, the grey guy is holding the rock in his left hand: Before X

After center, the rock (and the white guy) drifts evermore to the right: After X

share|improve this question
It would help if you provided screen shots of the problems occurring, and under what circumstances they occur. IE if your character disappears only when moving up or the background image jumps when it loops. Things like that will help locate problematic code. – UnderscoreZero Apr 29 '13 at 18:09
It gets wonky when I pass to the right of world.Center.X Feel free to check out the code and run it. – Mark Cidade Apr 30 '13 at 8:52
I also added images. – Mark Cidade Apr 30 '13 at 9:23

Rewrite this statement in a more readable fashion:

var x = p.X > v.Width     ? p.X - v.X/2: 
          p.X > s.Width/2   ? p.X - s.Width/2 :

And your problem is solved.

if p.X > v.Width then
    x = p.x - v.x/2;
    if p.x > s.width/2 then
        x = p.x - s.width/2;

Also, your viewRect should never have it's width or height changing. You seem to be trying to over complicate things.

You need a viewport offset for X and Y. You need a player position. The viewport offset is p.offset - viewport.size / 2 The viewport has a size.

You then want to draw from viewport offset (maybe - 1) to viewport offset + viewport size.

share|improve this answer
I didn't change the viewRect w * h. I just preferred using the h and w variables. – Mark Cidade Apr 30 '13 at 8:51
It doesnt seem like your solution worked. – Mark Cidade Apr 30 '13 at 9:24
And I just updated my code to a klugey fix. – Mark Cidade Apr 30 '13 at 9:36

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.