我如何测试Pygame中的碰撞?

问题描述 投票:1回答:2

我正在努力弄清碰撞在pygame中是如何工作的。我了解这与pygame.rect.colliderect有关,而且我可能已经很接近了,但是我希望有人能比我了解更多信息! :-)

这是我编写的一个简单程序,用于将一个微小的绿色方块引导到一个较大的红色方块上,并且我试图在两者相遇时实现碰撞检测,但在此阶段,everything可以工作,但碰撞除外。” >

提前感谢!

pygame.init()

import random #import random

size = (700,500) # set up the screen
screen = pygame.display.set_mode((size))

BLACK = (0,0,0) #define colours
WHITE = (255,255,255)
GREEN = (0,255,0)
RED =   (255, 0, 0)

class player(): #assign a player class
    def __init__(self):
        self.xpos = 450
        self.ypos = 250
        self.rect = pygame.Rect(self.xpos,self.ypos,5,5)
        self.xvel = 0
        self.yvel = 0
        self.colour = GREEN

    def update(self): #define a function to update the payer
        #self.xpos +=self.xvel  Ignore this bit. I implemented velocity, but it quickly flew off the screen
        #self.ypos +=self.yvel
        if player.rect.colliderect(obstacle.rect):    #<--------- this is the bit I think might be wrong?
            print("collision!")

    def draw(self): #define a function to draw the player
        pygame.draw.rect(screen, self.colour,[self.xpos,self.ypos,5,5])

class obstacle(): #define an obstacle class
    def __init__ (self):
        self.xpos = random.uniform(0,700)
        self.ypos = random.uniform(0,500)
        self.rect = pygame.Rect(self.xpos,self.ypos,20,20)
        self.colour = RED

    def draw(self): #define a function to draw the obstacle
        pygame.draw.rect(screen, self.colour,[self.xpos,self.ypos, 20,20])

player = player() #run an instance of the player class
obstacle = obstacle() #run an instance of the obstacle class
clock = pygame.time.Clock()


while True: #game loop
    for event in pygame.event.get(): #quit 
        if event.type == pygame.QUIT:
           pygame.display.quit()

#-----Game logic           
    keys = pygame.key.get_pressed() #check for key presses and do whatever
    if keys[pygame.K_LEFT]:
        player.xpos -= 1
    if keys[pygame.K_RIGHT]:
        player.xpos += 1
    if keys[pygame.K_UP]:
        player.ypos -= 1
    if keys[pygame.K_DOWN]:
        player.ypos += 1


    player.update() #Update the player - obstacle shouldn't need updating

#-----Drawing code

    screen.fill(BLACK) #draw screen black
    obstacle.draw() #draw the obstacle from the function
    player.draw() #draw the player from the function
    pygame.display.flip() #update

    clock.tick(60)'''




我正在努力弄清碰撞在pygame中是如何工作的。我了解这与pygame.rect.colliderect有关,而且我可能还很接近,但我希望感谢知道更多的人...

python pygame collision-detection
2个回答
1
投票

问题是您没有更新播放器矩形的位置,该矩形在检测到碰撞时会发生碰撞。您在更改xposypox时正在绘制矩形,但是矩形rect.xrect.y的坐标并未相应地更新。我换了线


0
投票

在这种情况下,请始终打印出无效的内容,即player.rect和障碍物.rect。您会看到您没有更新player.rect,它始终是>>

<rect(150, 150, 5, 5)>
© www.soinside.com 2019 - 2024. All rights reserved.