簡體   English   中英

我如何讓pygame碰撞起作用

[英]How do I get pygame collisions to work

我正在制作一只飛揚的小鳥副本,但無法獲得碰撞機制。 目前,我正在嘗試使用.coliderect()但我不確定100%如何使用。 這是兩個類。 我希望程序做些什么,或者當鳥和管道發生碰撞時只執行print('x') ,但是當它們此時發生碰撞時,該程序不執行任何操作或不輸出任何東西。

import pygame

vec = pygame.math.Vector2
BLACK = (0,0,0)
WIDTH = 500
HEIGHT = 400

pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Flappy Bird')
clock = pygame.time.Clock()

class Bird():

    def __init__(self):

        self.skin = pygame.image.load('bird2.png')
        self.rect = self.skin.get_rect()
        self.rect.center = (WIDTH / 2, HEIGHT / 2)

        self.vx = 0
        self.vy = 0

        self.pos = vec(WIDTH / 2, HEIGHT / 2)
        self.vel = vec(0, 0)
        self.acc = vec(0, 0)

    def update(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        window.fill(BLACK)
        self.acc = vec(0, 0.7) #having 0.5 adds gravity
        self.vy = 0

        keys = pygame.key.get_pressed()

        if keys[pygame.K_SPACE]:
            self.vel.y = -7

        if keys[pygame.K_LEFT]:
            self.acc.x = -0.5  #change to y to add vertical motion

        if keys[pygame.K_RIGHT]:
            self.acc.x = 0.5   #change to y to add vertical motion

        #applys friction
        self.acc.x += self.vel.x * -0.08 #FRICTION
        #motion equations
        self.vel += self.acc
        self.pos += self.vel + 0.5 * self.acc

        self.rect.center = self.pos

        window.blit(self.skin, self.pos)


class Pipe():

    def __init__(self,x,y):
        self.image = pygame.Surface((50,60))
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.pos = vec(x,y)

    def blit_pipe(self):
        window.blit(self.image, self.pos)

def border_check():
    if (flappy.pos.y)+32 > HEIGHT: #this is the very top of the flappy
        print("You are under\n")
        pygame.quit()
        quit()

    if flappy.pos.y < 0:
        print("You are over\n") #this is the very top of the flappy
        pygame.quit()
        quit()


pipey = Pipe(300,200)
pipey.blit_pipe()

pipey2 = Pipe(100,200)
pipey2.blit_pipe()

flappy = Bird()

window.blit(flappy.skin, flappy.pos)


while True:

    border_check()
    flappy.update()
    pipey.blit_pipe()
    pipey2.blit_pipe()

    if flappy.rect.colliderect(pipey.rect):
        print('x')

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

您永遠不會設置Pipe實例的rect的位置,因此它們仍位於默認坐標(0, 0) 有多種設置坐標的方法,例如,您可以將坐標作為topleft參數傳遞給get_rect

self.rect = self.image.get_rect(topleft=(x, y))

如果碰撞檢測出了問題,請打印區域以查看實際位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM