I need to assess objects adjacent to my current object. There may be one above, below, left and right of my current position. If my current position is (x, y)
, then my adjacent objects are at positions: (x-1, y)
, (x+1, y)
, (x, y-1)
, (x, y+1)
.
Is it better to calculate these 4 positions and then store them in a 2D array, traversing them with a for... in
loop:
int[][] adjacentObjects = {
{x-1, y},
{x+1, y},
{x, y-1},
{x, y+1} };
for (int[] adjacent : adjacentObjects) { ...
if (adjacent[0] == ...) // x coordinate
if (adjacent[1] == ...) // y coordinate
Or am I better off just having 4 near-identical if
statements? Each would be 4 lines, where the x
and y
coordinates are the only difference.
My current mindset is that the for... in
loop is cleaner, though not as readable, but I don't really know which is 'better.'
I've also thought about using another method where I'd pass the values of x
and y
but I also need access to another two 2D arrays in the current method, and it seems wasteful to send those as parameters to the new method as well.
I'm using Java, but I don't feel this is specific to any one language. Any help is greatly appreciated!
Aucun commentaire:
Enregistrer un commentaire