Pygame - 没有 Sprite 或类的子弹和敌人碰撞

Posted

技术标签:

【中文标题】Pygame - 没有 Sprite 或类的子弹和敌人碰撞【英文标题】:Pygame- bullet and enemy collision without Sprite or classes 【发布时间】:2019-08-12 05:05:54 【问题描述】:

在弄清楚如何进行子弹和敌人之间的碰撞检测时遇到问题。敌人本身是一个类,但子弹不是一个类的一部分。我无法使用内置的spritecollide 函数,因为我没有使用sprite.Sprite

我知道我必须检查对象图像的各自位置,以查看它们是否重叠,但不确定如何执行此操作。代码贴在下面:

   import pygame
    import math, random, sys, pygame.mixer, time
    from pygame.locals import *
    pygame.mixer.pre_init(44100, -16, 2, 2048)
    pygame.mixer.init()
    pygame.init()
    jump = False
    jump_offset = 0
    jump_height = 250

    #Defining colours
    BLACK = (   0,   0,   0)
    WHITE = ( 255, 255, 255)
    BLUE = ( 0, 0, 255)

    k = pygame.key.get_pressed()

    #Window Settings
    w = 1280
    h = 720 
    half_w = w /2
    half_h = h /2
    AREA = w*h

    #Initialising the window
    display = pygame.display.set_mode((w,h))
    pygame.display.set_caption("Cattleman") 
    Clock = pygame.time.Clock()
    FPS = 600

    bullets = []
    bulletSprite = pygame.image.load("Bullet1R.png").convert_alpha()
    bulletSprite = pygame.transform.scale(bulletSprite, (20,10))
    shot = pygame.mixer.Sound("pew1.wav")

    global scroll
    scroll = 0
    class Enemy(pygame.sprite.Sprite):
            def __init__(self,x,y,img,):
                    pygame.sprite.Sprite.__init__(self)
                    self.image = pygame.image.load("Enemy.png").convert_alpha()
                    self.image = pygame.transform.scale(self.image,(120,120))
                    self.rect = self.image.get_rect()

                    self.rect.x = x
                    self.rect.y = y
                    self.counter = 0

            def move(self):           
                    speed = 2
                    display.blit(self.image,(self.rect.x,self.rect.y))
                    if self.counter >= 0 and self.counter <= 300: #counter more then 0 but less than distance 
                           self.rect.x += speed + scroll
                    elif self.counter >= 300 and self.counter <= 600:
                            self.rect.x += scroll
                    elif self.counter >= 600 and self.counter <= 900: #counter is greater than distance but less than double the distance.
                           self.rect.x -= speed - scroll
                    elif self.counter >= 900 and self.counter <= 1200:
                            self.rect.x += scroll
                    else:
                           self.counter = 0
                    self.counter += 1 

    def do_jumping():
            global jump_height
            global jump
            global jump_offset
            if jump:
                    jump_offset += 6

                    if jump_offset >= jump_height:
                            jump = False
            elif jump_offset > 0 and jump == False:
                    jump_offset -= 6

    #------------------------MAIN PROGRAM LOOP------------------------#
    def game_loop():
        global jump
        global scroll
        background = pygame.image.load("background.png").convert()
        backgroundWidth, backgroundHeight = background.get_rect().size

        stageWidth = backgroundWidth #sets the area which the player can move in
        stagePosX = 0 #Records position of stage as the player moves

        startScrollPosX = half_w

        circleRadius = 25
        circlePosX = circleRadius

        playerPosX = circleRadius
        playerPosY = 602
        playerVelocityX = 0

        playersprite = pygame.image.load("player_spriteR2.png").convert_alpha()
        playersprite = pygame.transform.scale(playersprite, (130,130))
        playerMaxHealth = 100

        next_bullet_time = 0 #Prevents multiple bullets spawning at once.
        bullet_delay = 300 # 0.3 seconds
        direction = True
        gameX = 1000
        enemy = Enemy(210,515,"Enemy.png")
        enemy2 = Enemy(1505,515,"Enemy.png")
        k = pygame.key.get_pressed()

        while True:

            current_time = pygame.time.get_ticks()
            do_jumping()
            for event in pygame.event.get():
                    k = pygame.key.get_pressed()

            if k[K_RIGHT]:
                playerVelocityX = 3 #Moves the player right
                playersprite = pygame.image.load("player_spriteR2.png").convert_alpha()
                playersprite = pygame.transform.scale(playersprite, (130,130))
                direction = True
            if k[K_LEFT]:
                playerVelocityX = -3 #Moves the player left
                playersprite = pygame.image.load("player_spriteL2.png").convert_alpha()
                playersprite = pygame.transform.scale(playersprite, (130,130))
                direction = False
            if k[K_UP] and jump == False and jump_offset == 0:
                    jump = True
            if not k[K_RIGHT] and not k[K_LEFT]:
                    playerVelocityX = 0 #If no input detected, the player does not move
            if k[K_SPACE]:
                    if current_time > next_bullet_time:
                            shot.play()
                            next_bullet_time = current_time + bullet_delay
                            if not direction:
                                bullets.append([circlePosX-90, playerPosY-20 - jump_offset, -6 ])
                            else:
                                bullets.append([circlePosX+30, playerPosY-20 - jump_offset, 6])

            enemy_list = pygame.sprite.Group()
            enemy_list.add(enemy)
            enemy_list.add(enemy2)

            playerPosX += playerVelocityX
            scroll = 0
            if playerPosX > stageWidth - circleRadius-25: playerPosX = stageWidth - circleRadius-25
            if playerPosX < circleRadius+55:playerPosX = circleRadius+55
            if playerPosX < startScrollPosX: circlePosX = playerPosX
            elif playerPosX > stageWidth - startScrollPosX: circlePosX = playerPosX - stageWidth + w
            else:
                circlePosX = startScrollPosX
                stagePosX += -playerVelocityX
                scroll = -playerVelocityX

            for b in range(len(bullets)):
                bullets[b][0] += bullets[b][2]

            width = display.get_width()
            for b in [b for b in bullets if b[0] < 0 or b[0] > width]:
                    bullets.remove(b)

            rel_x = stagePosX % backgroundWidth
            display.blit(background,(rel_x - backgroundWidth, 0))
            if rel_x < w:
                    display.blit(background, (rel_x, 0))

            for bullet in bullets:
                    display.blit(bulletSprite, pygame.Rect(bullet[0], bullet[1], 0, 0))

            display.blit(playersprite, (int(circlePosX-80),playerPosY-100 - jump_offset))

            for e in enemy_list:
                    e.move()

            pygame.display.update()
            Clock.tick(FPS)
            display.fill(BLACK)
    game_loop()

有什么想法吗?

【问题讨论】:

@Pygasm 在下面给出了一个很好的答案。但是,如果您努力重构代码以使用 PyGame Sprites,它将在整个项目的其余部分中为您节省大量时间(并使代码更简洁)。 @Kingsley 这个。一旦我学会了如何创建一个可以工作的精灵框架,我在项目中可以执行的复杂性就大大增加了。 【参考方案1】:

如果您将子弹变成完全成熟的pygame.Rect() 对象,则可以使用pygame.Rect.colliderect。所以……

# Creating a new bullet
bullets.append(pygame.Rect(X, Y, width, height))

然后……

# Checking if a bullet has collided
for bullet in bullets:
    for enemy in enemy_list:
        if bullet.colliderect(enemy):
            # Do Damage or Killing code

【讨论】:

好吧,这看起来是个好主意,你能解释一下myPlayerOrEnemy 部分吗? 另外,只需放入 pygame.Rect 部分并得到此错误: bullets.append(pygame.Rect(circlePosX+30, playerPosY-20 - jump_offset, 6)) TypeError: Argument must be rect样式对象 @JackHarrison myPlayerOrEnemy 是一个占位符变量,把你想要子弹检查的矩形放在里面。至于pygame.Rect() 对象,我弄错了。像这样传递你需要的参数:bullets.append(pygame.Rect(X, Y, Width, Height)) 很酷,解决了第一个问题,我用我的enemy_list 替换了myPlayerorEnemy,因此它会检查每个敌人实例,并让它向外壳打印一条消息:if bullet.colliderect(enemy_list): print("collision detected") 但得到: 参数必须是 Rect 样式对象。我以为 id 已经把敌人的类变成了 rect 吗? @JackHarrison 问题在于您使用的是数组。我已经进行了编辑以显示如何解决该问题。

以上是关于Pygame - 没有 Sprite 或类的子弹和敌人碰撞的主要内容,如果未能解决你的问题,请参考以下文章

pygame 的精灵使用

pygame 精灵的行走及二段跳实现方法

pygame编组(精灵组)Group中的常用方法介绍

浅谈pygame.sprite的精灵碰撞

学习 Python 之 Pygame 开发魂斗罗

pygame.sprite.Group