2012-01-11 123 views
1

我的目标是让我的程序能够在球精灵碰到任何一个'g_ball'精灵时检测碰撞。代码明显地检测到了碰撞,并且我有“打印”语句来测试它......但是它始终在打印“进度”,即使这些精灵都没有触及。下面是代码:程序检测到碰撞,即使精灵不是字面上碰撞'pygame.sprite.collide_rect'

while 1: 
    screen.blit(background, (0,0)) 
    for event in pygame.event.get(): 
     if event.type == QUIT: 
      pygame.quit() 
      sys.exit() 


     if event.type == KEYDOWN: 
      if event.key == K_a: 
       m_x = -4 
       s+=1 
      elif event.key == K_d: 
       m_x = +4 
       s2+=1 
     if event.type == KEYUP: 
      if event.key == K_a: 
       m_x = 0 
      elif event.key == K_d: 
       m_x = 0 

    x+= m_x 
    y+= m_y  

    ball = pygame.sprite.Sprite() 
    ball.image = pygame.image.load('red_ball.png').convert() 
    ball.rect = ball.image.get_rect() 
    ball.image.set_colorkey((white)) 
    screen.blit(ball.image,(x,y)) 
    if x > 640: 
     x = 0 
    if x < 0: 
     x = 640 


    g_ball = pygame.sprite.Sprite() 
    g_ball.image = pygame.image.load('green_ball.png').convert() 
    g_ball.rect = g_ball.image.get_rect() 
    g_ball.image.set_colorkey(white) 
    screen.blit(g_ball.image,(50,t)) 
    t+=5 
    if t > 521: 
     t = 0 
    collision = pygame.sprite.collide_rect(ball, g_ball) 
    if collision == True: 
     print ('PROGRESS!!!') 

回答

0

那是因为你没有偏移设置的碰撞,你只有通过偏移screen.blit

您的固定代码将是这样的:

... 
ball.rect = ball.image.get_rect() 
ball.rect.topleft = (x, y) 
... 
g_ball.rect = g_ball.image.get_rect() 
g_ball.rect.topleft = (50, t) 
... 
0

nightcracker是正确的。你是否意识到你在这个循环中做了什么(它应该尽可能快地运行)?您正在创建2个新球,您从HD载入图像,将它们放到(0,0),然后在屏幕上的指定位置手动打印它们。这最后一部分意味着你将它们显示在某个地方,但不是它们的真实位置(你用ball.rect = ball.image.get_rect()设置了它们的真实位置)。他们真的在(0,0),并且一直在碰撞。

你将它们拍到屏幕的方式并不好,你应该使用渲染器。无论如何,你应该首先尝试一些教程,了解什么是Surface,什么是Sprite。要小心你在主循环中放置的东西(为什么你一直创造新球?他们可以在启动时创建一次),你的代码会更漂亮,你的FPS将增加