2017-09-14 22 views
2

我有一個叫Bullets的類,這些物體在使用pygame.sprite.spritecollide()命中時能夠摧毀其他精靈。我的問題是,我希望子彈'取消',即當他們擊中時互相摧毀,但是spritecollide()只會殺死其中一個,我需要兩個都消失。有沒有辦法做到這一點與spritecollide()或我需要別的嗎?如何在同一個pygame.sprite.Group中製作兩個擊中對象的子彈?

+2

您能告訴我您的碰撞代碼嗎?我傾向於在Pygame中不使用'dokill'參數或者'sprite'方法,因爲它在代碼中會很快混淆。簡單的'collide_rect()'功能好得多。 – Jerrybibo

回答

1

您可以將自定義回調函數作爲collided參數傳遞給pygame.sprite.spritecollidegroupcollide。在這種情況下,我使用groupcollide並通過bullets組兩次。回調函數bullet_collision只是爲了檢查兩個精靈不是同一個對象。

import pygame as pg 
from pygame.math import Vector2 


pg.init() 

BG_COLOR = pg.Color('gray12') 
BULLET_IMG = pg.Surface((9, 15)) 
BULLET_IMG.fill(pg.Color('aquamarine2')) 


class Bullet(pg.sprite.Sprite): 

    def __init__(self, pos, *sprite_groups): 
     super().__init__(*sprite_groups) 
     self.image = BULLET_IMG 
     self.rect = self.image.get_rect(center=pos) 
     self.pos = pg.math.Vector2(pos) 
     self.vel = pg.math.Vector2(0, -450) 

    def update(self, dt): 
     self.pos += self.vel * dt 
     self.rect.center = self.pos 
     if self.rect.bottom <= 0 or self.rect.top > 600: 
      self.kill() 


# Pass this callback function to `pg.sprite.groupcollide` to 
# replace the default collision function. 
def bullet_collision(sprite1, sprite2): 
    """Return True if sprites are colliding, unless it's the same sprite.""" 
    if sprite1 is not sprite2: 
     return sprite1.rect.colliderect(sprite2.rect) 
    else: # Both sprites are the same object, so return False. 
     return False 


class Game: 

    def __init__(self): 
     self.clock = pg.time.Clock() 
     self.screen = pg.display.set_mode((800, 600)) 

     self.all_sprites = pg.sprite.Group() 
     self.bullets = pg.sprite.Group() 

     self.done = False 

    def run(self): 
     while not self.done: 
      dt = self.clock.tick(30)/1000 
      self.handle_events() 
      self.run_logic(dt) 
      self.draw() 

    def handle_events(self): 
     for event in pg.event.get(): 
      if event.type == pg.QUIT: 
       self.done = True 
      if event.type == pg.MOUSEBUTTONDOWN: 
       if event.button == 1: 
        Bullet(pg.mouse.get_pos(), self.all_sprites, self.bullets) 
        # A second bullet with inverted velocity. 
        bullet2 = Bullet(pg.mouse.get_pos()-Vector2(0, 400), 
            self.all_sprites, self.bullets) 
        bullet2.vel = pg.math.Vector2(0, 450) 

    def run_logic(self, dt): 
     self.all_sprites.update(dt) 
     # Groupcollide with the same group. 
     # Pass the bullet_collision function as the `collided` argument. 
     hits = pg.sprite.groupcollide(
      self.bullets, self.bullets, 
      True, True, collided=bullet_collision) 

    def draw(self): 
     self.screen.fill(BG_COLOR) 
     self.all_sprites.draw(self.screen) 

     pg.display.flip() 


if __name__ == '__main__': 
    Game().run() 
    pg.quit() 
相關問題