i have been working on 2d game, kind of terraria, , have got stage ready collision detection. tried myself, it... well, strange. wondering if me this. store of blocks in 2d array:
block[][] map = new block[mw][mh]; where mw map width , mh map height (in terms of number of blocks). each block image displayed 16x16 pixels. here attempted, know wrong dont know need do.
private void checkcollision() { for(int x = -1; x <= 1; x++){ for(int y = -1; y <= 2; y++){ rectangle obj = new rectangle((int)block.getxonscreen(xblock+x), (int)block.getyonscreen(yblock+y), 16, 16); try{ if(main.map[(int) (xblock+x)][(int) (yblock+y)].solid && obj.intersects(bounds()){ if(y <= -1 && vely > 0){ vely = 0; system.out.println("collision below"); onground = true; }else if(y >= 2 && vely < 0){ vely = 0; system.out.println("collision above"); } if(x <= -1 && velx < 0){ velx = 0; system.out.println("collision left"); }else if(x >= 1 && velx > 0){ velx = 0; system.out.println("collision right"); } } }catch(exception e){} } } } i call method every tick so, doesn't collide player falls.
public void tick(){ xblock += velx; yblock += vely; vely += gravity; checkcollision(); } if knows how collision detection efficiently please can share me. thanks! :)
based on few javafx/swing applications once wrote, way want detect collision keeping track of object is, , when moves check see new location (old + movement count) not exceeding limits of map. if does, want reset position right on limit can go in other directions valid. if keep trying move outside of limits should keep resetting position.
so limit of page 500 pixels wide, in position 495, , each move 10, next time move in position 505, that's out of range. run check if(currentposition > limit) {reset position limit} currentposition set 500 right on border, , within limits.
Comments
Post a Comment