I am taking an experimental first shot at writing a simple side-scroller game. I have this code for re-centering the screen if the player moves too far in some direction.
Is there a better way to write it? I feel like I am abusing the language, but it worked out so nicely that I think it might be okay.
public void adjustFrameIfNecessary()
{
int dx, dy;
if ((dx = (GAME_WIDTH - GAME_WIDTH / 3) - player.x) < 0 || (dx = GAME_WIDTH / 3 - player.x) > 0 || (dx = 0) == 0);
if ((dy = (GAME_HEIGHT - GAME_HEIGHT / 3) - player.y) < 0 || (dy = GAME_HEIGHT / 3 - player.y) > 0 || (dy = 0) == 0);
if(dx != 0 || dy != 0)
{
for (Drawable shiftMe : drawables)
{
shiftMe.unconditionalShift(dx, dy);
}
}
}
EDIT
With regards to everyone’s input, in an attempt to make it more readable, I have changed it to this
public void adjustFrameIfNecessary()
{
int dx, dy;
assignX:
{
dx = (GAME_WIDTH - GAME_WIDTH / 3) - player.x;
if(dx < 0) break assignX;
dx = GAME_WIDTH / 3 - player.x;
if(dx > 0) break assignX;
dx = 0;
}
assignY:
{
dy = (GAME_HEIGHT - GAME_HEIGHT / 3) - player.y;
if(dy < 0) break assignY;
dy = GAME_HEIGHT / 3 - player.y;
if(dy > 0) break assignY;
dy = 0;
}
if (dx != 0 || dy != 0)
{
for (Drawable shiftMe : drawables)
{
shiftMe.unconditionalShift(dx, dy);
}
}
}
Is this better?
EDIT 2
public void adjustFrameIfNecessary()
{
int dx = calculateShift(GAME_WIDTH, frameReference.x);
int dy = calculateShift(GAME_HEIGHT, frameReference.y);
if (dx != 0 || dy != 0)
{
for (Drawable shiftMe : drawables)
{
shiftMe.unconditionalShift(dx, dy);
}
}
}
I think that it is clear now. Thanks everyone.
Unreadable, but I get your point. One thing, though: why not reuse the same check for both x and y? And by using the ternary operator you get one hack less.