我试图添加碰撞,但它不起作用

时间:2016-01-22 08:23:28

标签: python pygame collision

import pygame
import os,sys
import random
import math

img_path = os.path.join("punch.png")
img_blob = os.path.join("blob.png")

class Enemy(object):
    def __init__(self,x,y):
        super(Enemy,self).__init__()
        self.image = pygame.Surface([160,160])
        self.image.set_colorkey(black)
        self.image.blit(pygame.image.load(img_blob),(0,0))
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.speed = 2
    def move_towards_player(self,character):
        dx,dy = character.rect.x - self.rect.x,character.rect.y - self.rect.y
        dist = math.hypot(dx,dy)
        dx,dy = dx / dist,dy / dist
        self.rect.x += dx * self.speed
        self.rect.y += dy * self.speed
    def draw(self,surface):

        surface.blit(self.image,(self.rect.x,self.rect.y))
class character(pygame.sprite.Sprite):

    def __init__(self, x = 275, y = 250):

        super(character,self).__init__()
        self.image = pygame.Surface([160,160])
        self.image.set_colorkey(black)
        self.image.blit(pygame.image.load(img_path),(0,0))
        self.rect = self.image.get_rect()
        self.rect.x = x

        self.rect.y = y



    def movement(self):

        key = pygame.key.get_pressed()

        dist = 10

        if key[pygame.K_w]:

            self.rect.y -= dist

        elif key[pygame.K_s]:

            self.rect.y += dist

        if key[pygame.K_a]:

            self.rect.x -= dist

        elif key[pygame.K_d]:

            self.rect.x += dist


        if self.rect.x > 1110:

            self.rect.x = 1110

        if self.rect.y < 20:

            self.rect.y = 20

        elif self.rect.y > 710:

            self.rect.y = 710
        if self.rect.x <20:
            self.rect.x = 20
        elif self.rect.x == 1110 and self.rect.y > 300 and self.rect.y < 400:
            self.rect.x = 25
        if self.rect.y == 20 and self.rect.x >500 and self.rect.x < 600:
            self.rect.y = 715
        elif self.rect.x == 20 and self.rect.y > 300 and self.rect.y < 400:
            self.rect.x = 1090
        if self.rect.y == 710 and self.rect.x >500 and self.rect.x < 600:
            self.rect.y = 25

# top of left and right doors are y = 220, bottom of left and right doors are y = 240 # right side of top and bottom doors are x = 285, left of top and bottom doors are x = 260
def collide(self,enemy,enemy_list):
    if self.rect.colliderect(enemy.rect):
        enemy_list.remove(enemy)

def draw(self,surface):

    surface.blit(self.image,(self.rect.x,self.rect.y))






pygame.init()                               # Pygame is initialised (starts running)

players = pygame.sprite.Group()

screen = pygame.display.set_mode([1250,850]) # Set the width and height of the screen [width,height]

pygame.display.set_caption("My Game")       # Name your window

background_image = pygame.image.load("untilted.png")


done = False                                # Loop until the user clicks the close button.

clock = pygame.time.Clock()                 # Used to manage how fast the screen updates

black    = (   0,   0,   0)                 # Define some colors using rgb values.  These can be

white    = ( 255, 255, 255)                 # used throughout the game instead of using rgb values.



# Define additional Functions and Procedures here
score = 0
bird = character()
blob = Enemy(random.randint(10,700),random.randint(10,400))
enemies = [blob]

# -------- Main Program Loop -----------

while done == False:



    for event in pygame.event.get():        # Check for an event (mouse click, key press)

        if event.type == pygame.QUIT:       # If user clicked close window

            done = True                     # Flag that we are done so we exit this loop

# Update sprites here
    for blob in enemies:
        blob.move_towards_player(bird)
        bird.collide(blob,enemies)
        blob.draw(screen)
    bird.movement()

    screen.blit(background_image,[0,0])

    bird.draw(screen)
    blob.draw(screen)



    pygame.display.update()                   # Go ahead and update the screen with what we've drawn.

    clock.tick(20)                        # Limit to 20 frames per second
    score += 1
pygame.quit()                               # Close the window and quit.

当我运行代码时,blob(敌人)不会产生,但是当我在敌人身上取出敌人时,这被认为是碰撞,blob会产生并跟随。我已经尝试了许多碰撞的东西,但这是我第一次在pygame中创建游戏,所以我必须查看所有内容。

1 个答案:

答案 0 :(得分:0)

我猜你的问题是,有时你的敌人会直接在玩家旁边产生,所以会立即发生碰撞。我不知道你使用的图像是什么样的,但要确保它们不是太大,空间很大,因为你的碰撞不是像素完美,而是使用图像的整个尺寸/矩形。 / p>

否则,您的代码到目前为止应该可以正常工作,但您仍然可以稍微改进一下。例如,由于您已经为Sprite使用了character类,因此您还可以使用Group类使代码更简单(绘制/移动/碰撞检测)。

以下是它的样子:

import pygame
import os,sys
import random
import math

img_path = os.path.join("punch.png")
img_blob = os.path.join("blob.png")

class Actor(pygame.sprite.Sprite):

    def __init__(self, x, y):
        super(Actor,self).__init__()
        self.image = pygame.Surface([160,160])
        self.image.set_colorkey(black)
        self.image.blit(pygame.image.load(img_path),(0,0))
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.speed = 2

class Enemy(Actor):

    def __init__(self, x, y):
         super(Enemy, self).__init__(x, y)
         self.target = None

    def update(self, enemies):
        if self.target:
            dx,dy =  self.target.rect.x - self.rect.x,  self.target.rect.y - self.rect.y
            dist = math.hypot(dx,dy)
            dx,dy = dx / dist,dy / dist
            self.rect.x += dx * self.speed
            self.rect.y += dy * self.speed

class Character(Actor):

    def __init__(self, x = 275, y = 250):
        super(Character, self).__init__(x, y)
        self.speed = 10

    def update(self, enemies):

        pygame.sprite.spritecollide(self, enemies, True)

        key = pygame.key.get_pressed()

        if key[pygame.K_w]:
            self.rect.y -= self.speed
        elif key[pygame.K_s]:
            self.rect.y += self.speed
        if key[pygame.K_a]:
            self.rect.x -= self.speed
        elif key[pygame.K_d]:
            self.rect.x += self.speed

        if self.rect.x > 1110:
            self.rect.x = 1110

        if self.rect.y < 20:
            self.rect.y = 20

        elif self.rect.y > 710:
            self.rect.y = 710
        if self.rect.x <20:
            self.rect.x = 20
        elif self.rect.x == 1110 and self.rect.y > 300 and self.rect.y < 400:
            self.rect.x = 25
        if self.rect.y == 20 and self.rect.x >500 and self.rect.x < 600:
            self.rect.y = 715
        elif self.rect.x == 20 and self.rect.y > 300 and self.rect.y < 400:
            self.rect.x = 1090
        if self.rect.y == 710 and self.rect.x >500 and self.rect.x < 600:
            self.rect.y = 25


pygame.init()                               # Pygame is initialised (starts running)

players = pygame.sprite.Group()
screen = pygame.display.set_mode([1250,850]) # Set the width and height of the screen [width,height]
pygame.display.set_caption("My Game")       # Name your window
background_image = pygame.image.load("untilted.png")

done = False                                # Loop until the user clicks the close button.

clock = pygame.time.Clock()                 # Used to manage how fast the screen updates
black    = (   0,   0,   0)                 # Define some colors using rgb values.  These can be
white    = ( 255, 255, 255)                 # used throughout the game instead of using rgb values.

# Define additional Functions and Procedures here
score = 0
bird = Character()
blob = Enemy(random.randint(500,700),random.randint(300,400))
blob.target=bird
all_sprites = pygame.sprite.Group([blob, bird])
enemies = pygame.sprite.Group([blob])

# -------- Main Program Loop -----------
while done == False:

    for event in pygame.event.get():        # Check for an event (mouse click, key press)
        if event.type == pygame.QUIT:       # If user clicked close window
            done = True                     # Flag that we are done so we exit this loop

    screen.blit(background_image, (0, 0))

    all_sprites.update(enemies)
    all_sprites.draw(screen)

    pygame.display.update()                   # Go ahead and update the screen with what we've drawn.

    clock.tick(20)                        # Limit to 20 frames per second
    score += 1
pygame.quit()      

请注意主循环只需要调用all_sprites.updateall_sprites.draw,其余部分由类EnemyCharacter本身处理。