This site requires JavaScript, please enable it in your browser!
Greenfoot back
kiarocks
kiarocks wrote ...

2013/12/3

Best way for collision detection?

kiarocks kiarocks

2013/12/3

#
I have accidentally made an infinite loop with my current collision detector. I know there is a good way to do this. Here's the relevant code:
   for(Actor floor = getOneObjectAtOffset(0, 0, Block.class); floor != null; 
        floor = getOneObjectAtOffset(0, 0, Block.class)) {
            if(getOneObjectAtOffset(0, 1, Block.class) != null) {
                setLocation(getX(), getY() - 1);
            } else {
                setLocation(getX(), getY() + 1);
                break;
            }
        }
    Actor floor = getOneObjectAtOffset(0, 1, Block.class);
    if(floor == null) {
        setLocation(getX(), getY() + 1);
    }
Block is simply a Block that should be collided with. The for loop is getting stuck, presumably because of the ceiling made of blocks causing an infinite loop. Help?
danpost danpost

2013/12/3

#
I think the problem is in the way you are coding the 'for' statement. Better probably would be to use a 'while' statement. It would help to see the movement code also, but a basic way of dealing with collision follows (where 'ySpeed' is the vertical change in location of your actor each frame )
// preliminary code
int dir = Math.signum(ySpeed); // get direction (+/- 1)
setLocation(getX(), getY()+ySpeed; // move (fall or rise)
// deal with collision
while(getOneIntersectingOffset(Block.class) != null)
{
    setLocation(getX(), getY()-dir);
    ySpeed = 0; // momentum stopped
}
With this, you are always moving backward from the initial movement off the object collided with.
kiarocks kiarocks

2013/12/3

#
Movement code is a setLocation() based on the key down. I don't have the code with me right now.
kiarocks kiarocks

2013/12/4

#
I decided to use collision on move. It's much simpler.
You need to login to post a reply.