Original Post
Hello everyone, I've just started working on a little rpg but I'm having trouble with my collision detection. It works completely fine in four way movement but when two keys are pressed two sections of my code are hit and the player ends up being moved to a diagonal square. I know exactly why there is an issue here but I'm not sure of a better way of going about 2d collision detection.
any suggestion about how to fix this?
public void doCollisions(ArrayList<Polygon> intersectList,GameContainer c)
{
for(int i = 0;i<intersectList.size();i++)
{
if (c.getInput().isKeyDown(Input.KEY_RIGHT))
{
//saves the origional position of the object in case this attempt doesn't work
float origPos = getPosition().x;
//places the object at the end of the object it intersected
getPosition().x=intersectList.get(i).getMinX() - getPolygon().getWidth()-1;
//moves the collision polygon
getPolygon().setX(getPosition().x);
//checks to see if there is still an overlap
if (getPolygon().intersects(intersectList.get(i)))
{
//if there is an overlap undo what what we just did and attempt again
getPosition().x=origPos;
getPolygon().setX(getPosition().x);
}
}
if (c.getInput().isKeyDown(Input.KEY_LEFT))
{
float origPos = getPosition().x;
getPosition().x= intersectList.get(i).getMaxX()+1;
getPolygon().setX(getPosition().x);
if (getPolygon().intersects(intersectList.get(i)))
{
getPosition().x =origPos;
getPolygon().setX(getPosition().x);
}
}
if (c.getInput().isKeyDown(Input.KEY_UP))
{
float origPos = getPosition().y;
getPosition().y = getPosition().y =intersectList.get(i).getMaxY()+1;
getPolygon().setY(getPosition().y);
if (getPolygon().intersects(intersectList.get(i)))
{
getPosition().y=origPos;
getPolygon().setY(getPosition().y);
}
}
if (c.getInput().isKeyDown(Input.KEY_DOWN))
{
float origPos = getPosition().y;
getPosition().y = intersectList.get(i).getMinY() - getPolygon().getHeight()-1;;
getPolygon().setY(getPosition().y);
if (getPolygon().intersects(intersectList.get(i)))
{
getPosition().y=origPos;
getPolygon().setY(getPosition().y);
}
}
}
}
any suggestion about how to fix this?