gaowei1 发表于 2020-12-17 21:47:57

python86讲碰撞检测

本帖最后由 gaowei1 于 2020-12-17 22:09 编辑

大佬求解,为什么我照着视频敲的代码,碰撞检测时只有一个小球在动,其他4个都在原地鬼畜啊

import pygame
import sys
from pygame.locals import *
from random import *

class Ball(pygame.sprite.Sprite):
    def __init__(self,image,position,speed,bg_size):
      super().__init__()
      self.image = pygame.image.load(image).convert_alpha()
      self.rect= self.image.get_rect()
      self.rect.left ,self.rect.top = position
      self.speed = speed
      self.width,self.height = bg_size
      self.radius = self.rect.width / 2

    def move(self):
      self.rect = self.rect.move(self.speed)

      if self.rect.right < 0:
            self.rect.left = self.width

      elif self.rect.left > self.width:
            self.rect.right = 0

      elif self.rect.bottom < 0:
            self.rect.top = self.height

      elif self.rect.top > self.height:
            self.rect.bottom = 0



def main():
    pygame.init()
    ball_image = '1.png'
    bg_imagre = '2.png'

    running = True
    bg_size = width,height = 1024,681
    screen = pygame.display.set_mode(bg_size)
    pygame.display.set_caption('play the ball')
    background = pygame.image.load(bg_imagre).convert_alpha()

    balls = []
    group = pygame.sprite.Group()

    for i in range(5):
      position = randint(0,width-100),randint(0,height-100)
      speed =
      ball = Ball(ball_image,position,speed,bg_size)
      #检测球生成时是否发生碰撞
      while pygame.sprite.spritecollide(ball,group,False,pygame.sprite.collide_circle):
            ball.rect.left,ball.rect.top = randint(0,width-100),randint(0,height-100)
      balls.append(ball)
      group.add(ball)

    clock = pygame.time.Clock()

    while True:
      for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()


      screen.blit(background,(0,0))

      for each in balls:
            each.move()
            screen.blit(each.image,each.rect)

      for each in group:
            group.remove(each)
            if pygame.sprite.spritecollide(ball,group,False,pygame.sprite.collide_circle):
                each.speed = - each.speed
                each.speed = - each.speed

            group.add(each)

      pygame.display.flip()
      clock.tick(30)

if __name__ == '__main__':
    main()

小伤口 发表于 2020-12-30 15:44:37

第74行应该改为each
if pygame.sprite.spritecollide(ball,group,False,pygame.sprite.collide_circle):
if pygame.sprite.spritecollide(each,group,False,pygame.sprite.collide_circle):
页: [1]
查看完整版本: python86讲碰撞检测