pygame Отталкивание мячов
Пытаюсь заставить шары отталкиваться друг от друга, получилось вроде отследить момент столкновения (правильно ли я это сделал?), оттолкнуть их не получается, метод reflect почему-то не срабатывает. Что я делаю не так?
import pygame
import random
class Ball(pygame.sprite.Sprite):
def __init__(self, startpos, velocity, startdir):
super().__init__()
self.pos = pygame.math.Vector2(startpos)
self.velocity = velocity
print("startdir", startdir)
print("not norm", pygame.math.Vector2(startdir))
self.dir = pygame.math.Vector2(startdir).normalize()
print("norm", self.dir)
self.image = pygame.image.load("small_ball.png").convert_alpha()
self.rect = self.image.get_rect(center = (round(self.pos.x), round(self.pos.y)))
def reflect(self, NV):
self.dir = self.dir.reflect(pygame.math.Vector2(NV))
def update(self):
self.pos += self.dir * self.velocity
self.rect.center = round(self.pos.x), round(self.pos.y)
if self.rect.left <= 0:
self.reflect((1, 0))
if self.rect.right >= 700:
self.reflect((-1, 0))
if self.rect.top <= 0:
self.reflect((0, 1))
if self.rect.bottom >= 700:
self.reflect((0, -1))
pygame.init()
window = pygame.display.set_mode((700, 700))
pygame.display.set_caption('noname')
clock = pygame.time.Clock()
all_balls = pygame.sprite.Group()
start, velocity, direction = (200, 200), 10, (random.random(), random.random())
ball_1 = Ball(start, velocity, direction)
start, velocity, direction = (200, 200), 10, (random.random(), random.random())
ball_2 = Ball(start, velocity, direction)
all_balls.add(ball_1)
all_balls.add(ball_2)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
blocks_hit = pygame.sprite.groupcollide(all_balls, all_balls, False, False)
if blocks_hit:
for _, sprites_hit in blocks_hit.items():
if len(sprites_hit) > 1:
sprite_1 = sprites_hit[0]
sprite_2 = sprites_hit[1]
print("Столконвение")
sprite_2.reflect((0, 1)) # Ничего не происходит
all_balls.update()
window.fill(0)
pygame.draw.rect(window, (255, 0, 0), (0, 0, 700, 700), 1)
all_balls.draw(window)
pygame.display.flip()
