Marlon Dias - 7 months ago 58

Java Question

I'm making a tile-based rendering method for a game, using Java.

There is the possibility of the first row (and column) of tiles be partially drawn on screen and i want to know how many pixel of these tiles are on screen.

I came up with this (for checking the max X coordinates of broken tiles):

`int brokenX = xOffset; //xOffset can be any number`

while (brokenX < 0){

brokenX += tileSet.getTileSize(); //corrects if the number is negative

}

while (brokenX >= tileSet.getTileSize()){

brokenX -= tileSet.getTileSize(); //corrects if the number is too big

}

This works fine. But it seems like a waste of resources (considering it will be done twice for each frame).

Is there some

Answer

I'd suggest to use a library function. Obviously, it's an huge overkill for this task, but there's much more in a good library. My favorite is Guava and this is the `mod`

method:

```
int result = x % m;
return (result >= 0) ? result : result + m;
```

An example should make it clear. I'm trying the numbers `13, 3, -7, -17`

modulo `10`

, which all should return the same result.

`13 % 10 = 3`

, that's OK`3 % 10 = 3`

, still OK`-7 % 10 = -7`

is negative and unusable as index, but with`-7 % 10 + 10 = 3`

it's fine.`-17 % 10 + 10 = 3`

is fine, too.

So for `result < 0`

, or equivalently `m < 0`

, you need to add `m`

to get a positive result.

Source (Stackoverflow)