1
\$\begingroup\$

I have a game in which the enemy has to bounce of the edge, when it hits it. It is working fine, normally, but when I resize the window, the bouncing breaks. It doesn't bounce properly.

Bouncing works at its normal size. Resized, bouncing breaks.

In the image, the red enemy is not in the screen. How would I make it bounce off properly even after resizing the window?


Here is my BasicEnemy code:

public class BasicEnemy extends Enemy {

    public BasicEnemy(Player player, float x, float y) {

        super(player, new TextureRegion(), x, y, 5, 5);
        width = 16;
        height = 16;
    }

    @Override
    public void tick(float dt) {

        wrapPos();
        if (touchesPlayer())
            player.setHealth(player.getHealth() - 1);

        x += velX;
        y += velY;
    }

    @Override
    public void render(SpriteBatch batch, ShapeRenderer renderer) {

        renderer.setColor(Color.RED);
        renderer.rect(x - width/2, y-height/2, width, height);
    }
}

Here is my Enemy code:

public abstract class Enemy extends Entity {

    protected Player player;

    public Enemy(Player player, TextureRegion region, float x, float y, 
        float velX, float velY) {

        super(region, x, y, velX, velY);
        this.player = player;
    }

    @Override
    protected void wrapPos() {

        if (x > Gdx.graphics.getWidth() - width /2 || x < width/2) {

            //Here we flip the speed, so it bounces the other way.
            velX = -velX;
        }

        //Same as above, but with on the y-axis.
        if (y > Gdx.graphics.getHeight() -height/2 || y < height/2) {

            velY = -velY;
        }
    }

    protected boolean touchesPlayer() {

        return getBoundingBox().overlaps(player.getBoundingBox());
    }  
}
\$\endgroup\$
3

2 Answers 2

1
\$\begingroup\$

To explain @ShivGames answer, the reason why some viewports work and some don't is because they change the aspect ratio and limit the viewport size. In fact, all viewports "work" except that they cut off the screen, hence why the "walls" are not at the edges of the screen but actually closer / farther apart from the actual edge.

Take a look at the wiki entry for viewports and look at the images there. The gray part is the actual world that was being collided with while the black part is outside, and therefor not part of, the actual game.

\$\endgroup\$
0
\$\begingroup\$

All I had to do was make the viewport a StretchViewport or a FitViewport. ExtendViewport didn't work for some reason.

\$\endgroup\$

You must log in to answer this question.

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