I am making a putt putt game. I made the walls and the balls with classes and each class has a rect defining its position. All of the walls are in a list and I check the list using colliderect to see if the ball is hitting any of the walls. If so, depending on the wall (vertical or horizontal), I change the direction the ball is going. The problem is that occasionally, the ball will hit the wall and get stuck inside. I imagine that it is just continually colliding with the wall and keeps changing direction, making it just stay still.
Ive tried adding a cooldown, but even that doesn't always work. The speed of the ball shouldn't be the issue as if it moves 3px per frame, if would be moving that same speed out on the next frame after its direction was changed. However, slower speeds help but still dont completely solve this issue. Also, I am detection collisions before I move the ball on each frame.
for wall in walls:
if wall.type == "hwall":
if wall.rect.colliderect(ball.rect):
ball.y_change = -(ball.y_change)
elif wall.type == "vwall":
if wall.rect.colliderect(ball.rect):
ball.x_change = -(ball.x_change)
Here is the full code: https://pastebin.com/85Ge175i
ball.rect.left = wall.rect.right, if it moves right thenball.rect.right = wall.rect.leftSprite.Group()you could check collisin with all walls at once withoutforloop. And there is method that first move ball only on X and check with all walls (and eventually move it little back), next you move ball only on Y and check it with all walls again (and eventually move it little back). This way you can resolves some problems - ie. if you stuck in corner.update().(ball.x,ball.y)and(ball.rect.x, ball.rect.y). First you move ballball.x += ball.y_changebut later you check collision using old position inball.rect. You should use onlyball.rect-ball.rect.x += ball.y_changeand then it works correctly, almost ideal. If you slow down toclock.tick(10)then you can see that ball doesn't go inside wall. Sometimes it doesn't touch wall but it is problem forball.rect.left = wall.rect.right