Wie lasse ich den Ball richtig abprallen (Python/ pgzrun)?

Hallo liebe Community,

ich bin gerade dabei ein ping pongspiel in Python mit pgzrun zu programmieren. Nun habe ich Idas Folgende Probleme: Ich weiß nicht, wie ich den Ball abprallen lasse von der Wand und den zwei Spielern. Meine Idee war es den Winkel immer ca. +90 zu rechnen, wenn der etwas trifft. Dies funktionierte nur in bestimmten fällen richtig (z.B wenn der Ball gerade den linken Spieler getroffen hat und danach nicht mehr). Ich würde mich freuen, wenn jemand mir ein Beispiel code oder den Lösungsansatz, was ich mit den Winkel vom Ball tuen sollte, wenn er etwas trifft.

Code:

# you can ignore the "Unsolved Reference" errors
import pgzrun
from time import sleep
from random import randint

# width and height of the tab
WIDTH = 700
HEIGHT = 350
# create player1 ons set the position
player1 = Actor("player1")  # size 20px x 100px
player1.x = 65
player1.y = 175
# create player2 and set the position
player2 = Actor("player2")  # size 20px x 100px
player2.x = 635
player2.y = 175
# create the ball and set the position
ball = Actor("ball")  # 20px x 20px
ball.x = 350
ball.y = 175
ball.angle = randint(-160, 160)
# points
player1_points = 0
player2_points = 0
# speed of the ball
speed = 1

def draw():
    # draw the elements of the game
    screen.fill((12, 12, 12))  # black background
    player1.draw()
    player2.draw()
    ball.draw()
    screen.draw.text(f"{player1_points} : {player2_points}", (330, 25))

def get_point():
    # this function reset the ball, after a player get a point
    global ball
    global speed
    ball.x = 350
    ball.y = 175
    sleep(3)
    ball.angle = randint(-160, 160)
    speed = 1


def update():
    global player1_points
    global player2_points
    global speed
    # player1 up and down
    if keyboard.w and player1.y > 50:
        player1.y -= 7
    if keyboard.s and player1.y < 300:
        player1.y += 7
    # player2 up and down
    if keyboard.up and player2.y > 50:
        player2.y -= 7
    if keyboard.down and player2.y < 300:
        player2.y += 7
    # points
    if ball.x > 0:
        player2_points += 1
        get_point()
    if ball.x > 700:
        player1_points += 1
        get_point()

    if ball.colliderect(player1) or ball.colliderect(player2) or ball.y < 10 or ball.y > 340:
        # bounce
        

pgzrun.go()

Viele Grüße

Zerstoerer0711

programmieren, Code, Programmiersprache, Python, Python 3, Spiele programmieren, Pygame

Meistgelesene Fragen zum Thema Code