Demons
Demons

Reputation: 179

Python Turtle how to create collision

I am attempting to create pong using Turtle, however, I am having an issue with the collision system. I am using a basic pythagorean function for this, however, when the ball hits a bumber, it gets stuck at the bumper and starts shaking. I am not sure how to fix this problem. Here is the collision and bumper code.

turtle.register_shape('bar.gif')

lbump = turtle.Turtle()
lbump.color('white')
lbump.shape('bar.gif')
lbump.penup()
lbump.speed(0)
lbump.setposition(-285,0)

rbump = turtle.Turtle()
rbump.color('white')
rbump.shape('bar.gif')
rbump.penup()
rbump.speed(0)
rbump.setposition(285,0)

ball = turtle.Turtle()
ball.color('white')
ball.shape('circle')
ball.penup()
ball.speed(0)
ball.setposition(0,0)
ballspeedx = -5
ballspeedy = 0 #To test collison#

def isCollision(t1, t2):
    distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2))
    if distance < 30:
        return True
    else:
        return False

def ball_move():
    while True:
        global ballspeedy
        global ballspeedx
        x = ball.xcor() + ballspeedx
        y = ball.ycor() + ballspeedy
        if y > 285 or y < -285:
            ballspeedy *= -1

        if x < -295 or x > 295:
            x = 0
            y = 0

        if isCollision(lbump, ball):
            ballspeedx *= -1

        if isCollision(rbump, ball):
            ballspeedx *= -1
        ball.setposition(x,y)

Upvotes: 0

Views: 444

Answers (1)

Valentino
Valentino

Reputation: 7361

The reason it's likely this: when a collision is detected (isCollision returns True) and the sign of the x velocity is switched, the ball does not have the time to gain enough distance from the bumper until the next iteration of the loop. Hence, next iteration isCollision is still detecting a collision and changes again the sign of the velocity.
As a result, x velocity sign is switched each iteration from positive to negative and viceversa, and you see the shacking effect.

If I'm right, this edit is the simplest way that come to my mind to solve the issue:

if isCollision(lbump, ball):
    ballspeedx = abs(ballspeedx)

if isCollision(rbump, ball):
    ballspeedx = -1 * abs(ballspeedx)

Of course more elaborate solutions can be implemented.

Upvotes: 1

Related Questions