1
\$\begingroup\$

I am developing an iPhone game. There is a fountain that the user should not be able to walk through. Now, this question is about checking circle-point collision or anything like that. I am checking collision with CGRectIntersectsRect(character1.frame, fountain.frame).

But, here is the problem: If I prevent the person from moving; he will never be able to move. So, I tried combatting this with following:

    if (character.center.y > fountain.center.y && CGRectIntersectsRect(character1.frame, fountain.frame) && g == false) {
        g = true;
        character1.center = CGPointMake(character1.center.x, character1.center.y-0.1);
    }
    if (character.center.x > fountain.center.x && CGRectIntersectsRect(character1.frame, fountain.frame)) {
        character1.center = CGPointMake(character1.center.x-0.1, character1.center.y);
    }
    if (character.center.y < fountain.center.y && CGRectIntersectsRect(character1.frame, fountain.frame)) {
        character1.center = CGPointMake(character1.center.x, character1.center.y+0.1);
    }
    if (character.center.x < fountain.center.x && CGRectIntersectsRect(character1.frame, fountain.frame)) {
        character1.center = CGPointMake(character1.center.x+0.1, character1.center.y);
    }

This should check what side the character1 is intersecting the fountain and then make it so it is not intersecting the fountain by incrementing or decrementing the x or y coordinates of the characters it. But, this still gives weird results. It will move it diagonally across the fountain if keep holding down on the the top side of the fountain and also, it will keep moving it left other wise on the top of the fountain.

\$\endgroup\$

2 Answers 2

6
\$\begingroup\$

Speaking generally, the way this is handled is by moving you backwards along the collision normal. You find the axis the collision took place on (normal is a physics term, just think of it as the vector indicating the direction you penetrated the other object. Then you figure out how far you have to move back on that vector to no longer be colliding. See gpwiki for more information.

\$\endgroup\$
1
\$\begingroup\$

I would check for the collision before the character is moved to the new position. So that when you update the position of the character you know that it's valid.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ This is okay for slow moving objects, but anything that can move a sizable amount in a single frame will look weird. \$\endgroup\$
    – coderanger
    Jul 24, 2010 at 23:58
  • \$\begingroup\$ This isn't suitable for all types of game, but it is for many 2D games where characters move at constant speeds. It's certainly the easiest thing to do. \$\endgroup\$ Jul 25, 2010 at 1:39
  • \$\begingroup\$ Great points, I was just trying to make it simpler for his case. \$\endgroup\$
    – Steve T
    Jul 28, 2010 at 22:43

You must log in to answer this question.