I have already tried every possible way for removing this bug but all failed. The problem is that sometimes my player passes through the map tiles, i mean, the algorithm is like -- if not colliding, move in required direction; else if colliding, move in opposite direction. But sometimes the second condition fails i dont understand why.
private void movement(){ left=bindObject.getLeft(); right=bindObject.getRight(); up=bindObject.getUp(); down=bindObject.getDown(); bindObject.setColliding(colliding); lastHorz=bindObject.getLastHorz(); lastVert=bindObject.getLastVert(); //IF NOT COLLIDING if(colliding==false){ if(left==true){ x--; } else if(right==true){ x++; } if(up==true){ y--; } else if(down==true){ y++; } if(left==false && right==false){ bindObject.setLastHorz(null); } if(up==false && down==false){ bindObject.setLastVert(null); } } //IF COLLIDING if(colliding==true){ if(lastHorz=="l" && lastVert==null){ x++; } else if(lastHorz=="r" && lastVert==null){ x--; } else if(lastVert=="u" && lastHorz==null){ y++; } else if(lastVert=="d" && lastHorz==null){ y--; } else if(lastHorz=="l" && lastVert=="u" && y>=(int)cRec.getY()+49){ y++; } else if(lastHorz=="l" && lastVert=="u" && y<(int)cRec.getY()+49){ x++; } else if(lastHorz=="r" && lastVert=="u" && y>=(int)cRec.getY()+49){ y++; } else if(lastHorz=="r" && lastVert=="u" && y<(int)cRec.getY()+49){ x--; } else if(lastHorz=="l" && lastVert=="d" && y<=(int)cRec.getY()-49){ y--; } else if(lastHorz=="l" && lastVert=="d" && y>(int)cRec.getY()-49){ x++; } else if(lastHorz=="r" && lastVert=="d" && y<=(int)cRec.getY()-49){ y--; } else if(lastHorz=="r" && lastVert=="d" && y>(int)cRec.getY()-49){ x--; } } } private void collision(){ for(Rectangle temp: tileList){ if(player.intersects(temp)){ colliding=true; cRec=temp; break; } } if(cRec!=null){ if(player.intersects(cRec)==false){ colliding=false; } } }
, where bindObject is a class which contains key bindings of following keys:-
left arrow key (when pressed) , left arrow key (when released),
right arrow key (when pressed), right arrow key (when released),
up arrow key (when pressed), up arrow key (when released),
down arrow key (when pressed), down arrow key (when released)