Question

I´m very frustrated because I can´t draw the Ground like in Flappy Bird... I try to use this method:

private void drawGround(){  
    for(Rectangle mRectangleGroundHelper : mArrayGround){
        if(spawnGround & mRectangleGroundHelper.x<0){ // spawn Ground if the actual ground.x + ground.width() is smaller then the display width.
            mArrayGround.add(mRectangleGroundHelper);
            spawnGround = false;
        }
    }
    for(Rectangle mRectangleGroundHelper : mArrayGround){
        if(mRectangleGroundHelper.x < -mTextureGround.getWidth()){ // set boolean to true, if the actual ground.x completely hide from display, so a new ground can be spawn
            spawnGround = true;
        }
    }

    for(Rectangle mRectangleGroundHelper : mArrayGround){ // move the ground in negative x position and draw him...
        mRectangleGroundHelper.x-=2;
        mStage.getSpriteBatch().draw(mTextureGround, mRectangleGroundHelper.x, mRectangleGroundHelper.y);
    }
}

The once result is, that when the ground.x hits the left side from the display, the ground moves faster in negative x. So what is the error in my method?

Was it helpful?

Solution

mRectangleGroundHelper.x-=2;

This is a scary piece of code. In general you probably shouldn't be moving your ground at all, because that basically requires moving the whole world.

Instead, create a "Viewport" position, which is really just an X variable. As the game moves forward, you move your viewport forward (really just X++), and draw all your objects relative to that.

Then you don't need to "spawn" any ground at all. You either just draw it or you don't.

Here's a rough example based on a lot of assumptions about your data...

private void drawGround(){
    viewport.x += 2;
    for(Rectangle r : mArrayGround) {
        if(r.x + r.width > viewport.x && r.x < viewport.x + viewport.width) {
            mStage.getSpriteBatch().draw(mTextureGround, viewport.x - r.x, r.y);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top