import pygame import math pygame.init() # Fenster erstellen width, height = 800, 600 screen = pygame.display.set_mode((width, height)) pygame.display.set_caption('Kollision Ball-Wand') # Farben WHITE = (255, 255, 255) RED = (255, 0, 0) # Ball Attribute ball_radius = 20 ball_pos = [100, 300] ball_speed = [2, 2] # Wand Attribute (Beispiel: Rechteckige Wand) wall_width = 200 wall_height = 20 wall_pos = [400, 300] # Beispielposition wall_rotation_angle = 45 # Beispielwinkel in Grad def rotate_point(pos, angle, pivot): """Rotiert einen Punkt um einen Pivot-Punkt""" x, y = pos pivot_x, pivot_y = pivot s = math.sin(math.radians(angle)) c = math.cos(math.radians(angle)) x -= pivot_x y -= pivot_y new_x = x * c - y * s new_y = x * s + y * c x = new_x + pivot_x y = new_y + pivot_y return x, y def check_collision(ball_pos, ball_radius, wall_pos, wall_width, wall_height, wall_rotation_angle): """Überprüft Kollision zwischen Ball und Wand""" rotated_wall_points = [] for i in range(4): x = wall_pos[0] + wall_width * (i // 2) * ((i % 2) * 2 - 1) y = wall_pos[1] + wall_height * (i % 2) * ((i // 2) * 2 - 1) rotated_point = rotate_point((x, y), wall_rotation_angle, wall_pos) rotated_wall_points.append(rotated_point) for i in range(0, len(rotated_wall_points)): x1, y1 = rotated_wall_points[i] x2, y2 = rotated_wall_points[(i + 1) % len(rotated_wall_points)] d = ((x2 - x1) * (ball_pos[1] - y1) - (y2 - y1) * (ball_pos[0] - x1)) / math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) if abs(d) < ball_radius: return True return False running = True while running: screen.fill(WHITE) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Bewegung des Balls ball_pos[0] += ball_speed[0] ball_pos[1] += ball_speed[1] # Kollisionsprüfung mit der Wand if check_collision(ball_pos, ball_radius, wall_pos, wall_width, wall_height, wall_rotation_angle): # Hier Berechnung des Ausfallswinkels nach Kollision # Beispiel: Einfacher Winkelreflektion, um den Ball abzuprallen ball_speed[0] *= -1 ball_speed[1] *= -1 # Zeichne die rotierte Wand rotated_wall_points = [rotate_point((wall_pos[0] + wall_width / 2, wall_pos[1] - wall_height / 2), wall_rotation_angle, wall_pos), rotate_point((wall_pos[0] + wall_width / 2, wall_pos[1] + wall_height / 2), wall_rotation_angle, wall_pos), rotate_point((wall_pos[0] - wall_width / 2, wall_pos[1] + wall_height / 2), wall_rotation_angle, wall_pos), rotate_point((wall_pos[0] - wall_width / 2, wall_pos[1] - wall_height / 2), wall_rotation_angle, wall_pos)] pygame.draw.polygon(screen, RED, rotated_wall_points) # Zeichne den Ball pygame.draw.circle(screen, RED, (int(ball_pos[0]), int(ball_pos[1])), ball_radius) pygame.display.flip() pygame.quit()