1
\$\begingroup\$

The bug here is that my background kind of offset a bit itself from where it should draw and so I have this line. I have some troubles understanding why I get this bug when I set a speed that is different then 1,2,4,8,16,...

enter image description here

In main class I set the speed depending on the player speed

 bgSpeed = -(int)playerMoveSpeed.X / 10;

and here's my background class

class ParallaxingBackground
    {
        Texture2D texture;
        Vector2[] positions;
        public int Speed { get; set;}

        public void Initialize(ContentManager content, String texturePath, int screenWidth, int speed)
        {
            texture = content.Load<Texture2D>(texturePath);
            this.Speed = speed;
            positions = new Vector2[screenWidth / texture.Width + 2];
            for (int i = 0; i < positions.Length; i++)
            {
                positions[i] = new Vector2(i * texture.Width, 0); 
            }
        }
        public void Update() {
            for (int i = 0; i < positions.Length; i++)
            {
                positions[i].X += Speed;
                if (Speed <= 0)
                {
                    if (positions[i].X <= -texture.Width)
                    {
                        positions[i].X = texture.Width * (positions.Length - 1);
                    }
                }
                else
                {
                    if (positions[i].X >= texture.Width*(positions.Length - 1))
                    {
                        positions[i].X = -texture.Width;
                    }
                }
            }
        }
        public void Draw(SpriteBatch spriteBatch)
        {
            for (int i = 0; i < positions.Length; i++)
            {
                spriteBatch.Draw(texture, positions[i], Color.White);
            }
        }

    }
\$\endgroup\$
4
\$\begingroup\$

Your problem happens when you reuse the background and put it the other side. Change this:

 if (positions[i].X <= -texture.Width)
 {
      positions[i].X = texture.Width * (positions.Length - 1);
 }

To this:

 if (positions[i].X <= -texture.Width)
 {
      positions[i].X += texture.Width * positions.Length;
 }

So, add (+=) instead of overwrite (=).

Same here, change this:

if (positions[i].X >= texture.Width*(positions.Length - 1))
{
     positions[i].X = -texture.Width;
}

To this:

if (positions[i].X >= texture.Width*(positions.Length - 1))
{
     positions[i].X -= texture.Width * positions.Length;
}

Don't forget to get rid of the - 1 two times.

| improve this answer | |
\$\endgroup\$

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.