game-makerponggmlgame-maker-language

Ball gets stuck inside paddle in pong clone (Gamemaker)


I am currently making a Pong clone in gamemaker (My first stand alone project in gamemaker).

When the ball collides with the paddle, I reverse the x_speed (reversing its direction by taking it * -1). However, when the ball hits the top or bottom of the paddle, the ball becomes stuck inside, constantly changing its x_speed but never getting out of the paddle.

My question is not so much as what is the problem, but is there a practical way of getting around this problem?

I have tried (but failed) to implement the place_meeting method and I have tried a couple of other methods to detect if the ball has hit the top or bottom of the paddle so that I can adjust it's x and y positions accordingly.

If anyone has ideas (I don't necessarily need the code for the solution, just the idea so that I can implement it in my game. Here is what I have so far.

I have tried other solutions but none of them even came close, so no point in showing them here. If you need any other snippets of code from my program, just ask.

Step for the ball:

//Checking if it touches the borders of the play area
if (x <= 0) {
    x_speed *= -1;
    obj_score_left.gameScore += 1;
}
if (x + width >= room_width) {
    x_speed *= -1;
    obj_score_right.gameScore += 1;
}
if (y <= 0) y_speed *= -1;
if (y + height >= room_height) y_speed *= -1;

//Adds the x and y speeds to x and y
x += x_speed;
y += y_speed;

Solution

  • It would be usefull to have the script for your paddle too, since the collision which is causing your problem isn't shown here but I'll try wide-range solutions you should try implementing.

    The first step that should help a lot no matter what your situation is would be to force the ball at the right distance from your paddle when it collides, since it shouldn't be inside of it anyway. Something like this

    On collision:

    ball.x = paddle.x+paddle.width+ball.width
    

    Something that might help too would be to make sure the x_speed can only ever be in the opposite direction from the paddle, either by using point_direction() or abs()

    On collision:

    direction = point_direction(paddle.x,paddle.y,ball.x,ball.y) 
    //would require using native direction and speed variables rather than x_speed and y_speed
    

    or:

    x_speed = abs(xspeed) //for the left paddle
    x_speed = -abs(xspeed) //for the right paddle
    

    Without knowing more about your actual code this is all I can suggest.