Как мне проверить на столкновение в Pygame? - PullRequest
1 голос
/ 31 марта 2020

Я изо всех сил пытаюсь понять, как столкновения работают в пигме. Я понимаю, что это как-то связано с pygame.rect.colliderect, и я, вероятно, довольно близок, но я был бы признателен тому, кто знает немного больше, чем я, глядя на него! : -)

Вот простая программа, которую я написал, чтобы направить крошечный зеленый квадрат на больший красный квадрат, и я пытаюсь реализовать обнаружение столкновений, когда они встречаются, но на этом этапе все работает, кроме столкновений.

Заранее спасибо !!

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)'''




Ответы [ 2 ]

1 голос
/ 31 марта 2020

Проблема в том, что вы не обновляете положение прямоугольника вашего игрока, на что смотрит коллизия при обнаружении коллизии. Вы рисовали прямоугольник при изменении xpos и ypox, но координаты для вашего прямоугольника rect.x и rect.y не обновлялись соответствующим образом. Я изменил линии

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

на

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

и

    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

на

    if keys[pygame.K_LEFT]:
        player.rect.x -= 1
    if keys[pygame.K_RIGHT]:
        player.rect.x += 1
    if keys[pygame.K_UP]:
        player.rect.y -= 1
    if keys[pygame.K_DOWN]:
        player.rect.y += 1

, чтобы координаты прямоугольника игрока были быть обновленным.

0 голосов
/ 31 марта 2020

В этих случаях всегда распечатывайте то, что не работает, т.е. Вы увидите, что вы не обновляете player.rect, который всегда

<rect(150, 150, 5, 5)>

Поскольку он не перекрывается с препятствием.rect, которое всегда

<rect(34, 204, 20, 20)>

, столкновение не обнаружено. * +1007 *

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...