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 https://vanillity.kilnhg.com/Code/Repositories/Group/Aremac

Looks like this:

      var s = game.gd.Viewport.Bounds;
      var g = game.world.Bounds;
      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 = game.world.Bounds;
     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

  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Apr 29 '13 at 18:09
  • \$\begingroup\$ It gets wonky when I pass to the right of world.Center.X Feel free to check out the code and run it. \$\endgroup\$ Apr 30 '13 at 8:52
  • \$\begingroup\$ I also added images. \$\endgroup\$ 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.

  • \$\begingroup\$ I didn't change the viewRect w * h. I just preferred using the h and w variables. \$\endgroup\$ Apr 30 '13 at 8:51
  • \$\begingroup\$ It doesnt seem like your solution worked. \$\endgroup\$ Apr 30 '13 at 9:24
  • \$\begingroup\$ And I just updated my code to a klugey fix. \$\endgroup\$ Apr 30 '13 at 9:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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