Skip to main content
GameDev.net gamedev.net
🔒 Locked

Collision Detection

Started by Hollandera Apr 22, 2012 at 5:52 PM 1 replies 1.1k views
Original Post
Hollandera
Hollandera
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?
jbcode3
jbcode3
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...
}
Hollandera
Hollandera
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.