[Python] How to make turtle detect which side it collided on

Discussão em 'Python' iniciado por Stack, Julho 22, 2025.

  1. Stack

    Stack Membro Participativo

    Here is a MRE of my code:

    from turtle import Turtle, Screen
    import time
    import random

    # --------------- GLOBAL VARIABLES --------------------
    speed_x = 20
    speed_y = 20
    bricks = []


    def check_collision():
    global speed_x, speed_y, bricks

    if ball.xcor() > (window.window_width() / 2) - 20 or ball.xcor() < -(window.window_width() / 2) + 20:
    speed_x *= -1
    elif ball.ycor() > (window.window_height() / 2) - 20 or ball.ycor() < -(window.window_height() / 2) + 20:
    speed_y *= -1
    elif abs(paddle.xcor() - ball.xcor()) < 20/2 + 150/2 and abs(paddle.ycor() - ball.ycor()) < 20/2 + 60/2:
    if abs(paddle.xcor() - ball.xcor()) == 20/2 + 150/2:
    speed_x *= -1
    else:
    speed_y *= -1


    def game_loop():
    ball.goto(ball.xcor() + speed_x, ball.ycor() + speed_y)
    check_collision()

    window.update()

    window.ontimer(game_loop, 1)

    def move_right():
    paddle.setx(paddle.xcor() + 25)


    def move_left():
    paddle.setx(paddle.xcor() - 25)


    window = Screen()

    time.sleep(2)

    ball = Turtle(shape='circle')

    ball.pu()
    ball.speed(0)
    ball.goto(0, -300)

    ball.speed(0)
    ball.left(random.randint(45, 135))

    paddle = Turtle(shape='square')
    paddle.speed(0)
    paddle.goto(0, -400)
    paddle.shapesize(1, 7.5, 3)
    paddle.up()


    window.listen()
    window.onkeypress(move_right, 'Right')
    window.onkeypress(move_left, 'Left')
    window.onkeypress(move_right, 'd')
    window.onkeypress(move_left, 'a')


    game_loop()

    window.mainloop()


    Is it possible to detect if the ball hit the side (the short one) of the paddle? The reason I need this is since if It collides on the left side of the paddle, I want to ball x to change and not the y. In my code, the if abs(paddle.xcor() - ball.xcor()) == 20/2 + 150/2: is my attempt to recognize the side and the top (big side).

    Continue reading...

Compartilhe esta Página