java - Find a specific object at a specific coordinate in ArrayList -


im working on 2d tile-based game , i've come point need optimise code quit bit. im adding lot of different elements in javas list such trees, rocks , on. reason why elements not static tile because want player able interact elements. therefor elements has own object , stored in list.

the problem whenever want interact specific element in built in list in java have create for-loop , go through every single element in list find right element @ right coordinates. (such collision , on.)

the way this:

list<element> elements = new arraylist<element>();   public element getelementonpixel(int x, int y){`          for(int = 0; < elements.size(); i++){              int xx = elements.get(i).getx() * game.tile_size;             int yy = elements.get(i).gety() * game.tile_size;             int w = xx + elements.get(i).width;             int h = yy + elements.get(i).height;              if(x >= xx && x < w && y >= yy && y < h) {                 return elements.get(i);             }          }         return null;     } 

as can see above have go thought whole list until find right element @ right coordinate. heres problem pops because have alot of elements in game. question follows:

is there other way find specific element @ specific coordinate in javas built in lists?

you make imaginary make kind of grid of game:

like here 8 cols, 4 rows // 8 x-positions, 4 y-positions

[e][ ][ ][ ][ ][ ][ ][ ] [ ][ ][ ][ ][ ][e][ ][ ] [ ][ ][e][ ][e][ ][ ][ ] [e][ ][ ][ ][ ][ ][ ][ ] 

and align 1 row (list) ->

[e][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][e][ ][ ][ ][ ][e][ ][e][ ][ ][ ][e][ ][ ][ ][ ][ ][ ][ ] 

if want element on (x,y). take element:

(x,y) -> list.get(y-1 * "overall row-length" + x) 

example:

if want  element in position x = 5, y = 3 (5,3) -> list.get(3-1 * 8 + 5) = list.get(21) 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -