Player Sticking to Walls

Hey guys,

I've been trying to make a game and I ran into an interesting problem. I have currently programmed a player that can move around, a box that represents a wall, and a collision detection function. My problem is that the player will stop when he collides with a wall, but then he can't move away or slide along it. So how do I get rid of this "sticky" wall?

Collision Detection Function

1
2
3
4
5
6
7
8
9
10
11
12
bool GameSys::check_collision( SDL_Rect A, SDL_Rect B )
{
    if ( ( A.y <= ( B.y + B.h ) ) &&
         ( ( A.y + A.h ) >= B.y ) &&
         ( A.x <= ( B.x + B.w ) ) &&
         ( ( A.x + A.w ) >= B.x ) )
    {
        return true;
    }

    return false;
}



Detect Collision (transfers collision detection results to the player class)

1
2
3
4
void Player::detect_collision( bool co )
{
    collision = co;
}



Player Movement Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void Player::move_player()
{
    plyr_to.x += plyr_speedX;
    plyr_to.y += plyr_speedY;

    plyr_co_box.x += plyr_speedX;
    plyr_co_box.y += plyr_speedY;

    if ( plyr_co_box.x <= 0 || ( plyr_co_box.x + plyr_co_box.w ) >= 640 || collision == true )
    {
        plyr_to.x -= plyr_speedX;

        plyr_co_box.x -= plyr_speedX;
    }

    if ( plyr_co_box.y <= 0  || ( plyr_co_box.y + plyr_co_box.h ) >= 480 || collision == true )
    {
        plyr_to.y -= plyr_speedY;

        plyr_co_box.y -= plyr_speedY;
    }
}


Any help or comments are welcome. If you have a question or would like more info, please ask. Thanks :D
You can't treat a collision as if the current move made the collision. The previous move made the collision. So, handling it in the code that handles the current move going out of bounds (and coincidentally leaves the player in the same place he started in) won't work.
Last edited on
Ok, I modified the player movement function and now he doesn't usually walk through walls anymore. However he bounces off of the walls instead of stopping smoothly, and there's a chance that he will get caught in the wall and all of his movements get reversed. How do I fix this?

Player Movement Function #2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
void Player::move_player()
{
    if ( plyr_co_box.x <= 0 || ( plyr_co_box.x + plyr_co_box.w ) >= 640 || collision == true )
    {
        plyr_to.x -= plyr_speedX;

        plyr_co_box.x -= plyr_speedX;
    }
    else
    {
        plyr_to.x += plyr_speedX;

        plyr_co_box.x += plyr_speedX;
    }

    if ( plyr_co_box.y <= 0  || ( plyr_co_box.y + plyr_co_box.h ) >= 480 || collision == true )
    {
        plyr_to.y -= plyr_speedY;

        plyr_co_box.y -= plyr_speedY;
    }
    else
    {
        plyr_to.y += plyr_speedY;

        plyr_co_box.y += plyr_speedY;
    }
}
Last edited on
Topic archived. No new replies allowed.