Sign in to follow this  
GameGeazer

Collision Detection

Recommended Posts

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.
[CODE]
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);
}
}
}
}
[/CODE]

any suggestion about how to fix this?

Share this post


Link to post
Share on other sites
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:

[code]
if(KeyDown(Left))
{
do Left collision...
}
else if (KeyDown(Right))
{
do Right collision...
}
else if (KeyDown(Up))
{
do Up collision...
}
else
{
do Down collision...
}
[/code]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this