I'm coding for a game and want the background to repeat itself.
xOffset = (int) (camera.getX() % WIDTH);
g.drawImage(bgInv, xOffset - WIDTH, 0, WIDTH, HEIGHT, null);
g.translate(xOffset, 0);
g.drawImage(bg, 0, 0, WIDTH, HEIGHT, null);
g.translate(-xOffset, 0);
g.drawImage(bgInv, xOffset + WIDTH, 0, WIDTH, HEIGHT, null);
The first drawImage
draws when the camera's X is negative
and the third when the camera's X is positive.
The problem is that when I'm moving and the xOffset
goes from WIDTH
to 0, it seems like there's a "wrap".
The console is outputting xOffset
I know it is because I'm using modulo to get xOffset
but I didn't figure out a better way...
Thanks in advance
If I understood correctly, what you want to repeat is a 2 * WIDTH
by HEIGHT
image, where the left half is the background image and the right half is the same image horizontally inverted.
So what you can do is the following:
xOffset = (int) (camera.getX() % (2 * WIDTH));
// draw the background image at x = xOffset - 2 * WIDTH
g.drawImage(bg, xOffset - 2 * WIDTH, 0, WIDTH, HEIGHT, null);
g.drawImage(bgInv, xOffset - WIDTH, 0, WIDTH, HEIGHT, null);
// draw the background image at x = xOffset
g.drawImage(bg, xOffset, 0, WIDTH, HEIGHT, null);
g.drawImage(bgInv, xOffset + WIDTH, 0, WIDTH, HEIGHT, null);