Collision Detection

Started by
1 comment, last by Hollandera 11 years, 12 months ago
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.

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?
Advertisement
I take it that you only want your player to move in only one of four directions; Up, Down, Left, Right.

The most simple solution for this would be to change your collision check to only check 1 key each frame. For example:


if(KeyDown(Left))
{
do Left collision...
}
else if (KeyDown(Right))
{
do Right collision...
}
else if (KeyDown(Up))
{
do Up collision...
}
else
{
do Down collision...
}
Sorry If I wasn't clear above, my code works perfectly fine for 4-way collisions but I would like to make my game 8-way.

This topic is closed to new replies.

Advertisement