I’m working on making a pong game as an exercise, and i’m trying to handle the ball direction after it hits the paddle, I want the ball to go straight if it hits the center of the paddle and to go up with an angle 135 if it hits the upper segment and to go down with an angle 225 if it hits the lower segment.
I couldn’t find any function that can help me to solve this issue in the turtle library,
I need a functionality that can help me to determine where did the ball hits the paddle.
appreciate the help.
I tried to use the distance function but the problem that it gives me the same distance if the ball reaches the upper segment or the lower one.
import time
import turtle
turtle.setup(startx=2200, width=900)
turtle.tracer(0)
class Ball(turtle.Turtle):
def __init__(self):
super().__init__()
self.shape('circle')
self.penup()
# def move(self):
# """Moves the ball."""
# self.forward(20)
# # if self.xcor() > 560:
# # self.bounce(angle=180)
# # elif self.xcor() < -560:
# # self.bounce(angle=0)
#
# def bounce(self, angle):
# """Bounce the ball when it hits the paddles or the ceiling."""
# self.setheading(angle)
# self.forward(20)
#
# def collision(self):
# pass
#
# def up(self):
# self.sety(self.ycor() + 1)
#
# def down(self):
# self.sety(self.ycor() - 1)
#
# def go_right(self):
# self.setx(self.xcor() + 1)
#
# def go_left(self):
# self.setx(self.xcor() - 1)
class PaddlePart(turtle.Turtle):
"""Represents the paddle part"""
def __init__(self):
super().__init__()
self.shape('square')
self.shapesize(stretch_wid=6, stretch_len=1)
self.penup()
paddle_part1 = PaddlePart()
paddle_part1.setx(20)
print(paddle_part1.ycor())
ball = Ball()
# turtle.listen()
# turtle.onkeypress(fun=ball.up, key='Up')
# turtle.onkeypress(fun=ball.down, key='Down')
# turtle.onkeypress(fun=ball.go_right, key='Right')
# turtle.onkeypress(fun=ball.go_left, key='Left')
while True:
print(ball.distance(paddle_part1))
turtle.update()
time.sleep(0.01)
# turtle.mainloop()
Abdallah Sarayrah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.