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.
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());
}
}