我寫了一個小測試來感受pygame中的碰撞檢測。我的球員正確地移動並停在發生碰撞的岩石上,但是當我到達岩石時,我不能再離開。你們知道這是爲什麼嗎?這是我的測試代碼:pygame中的碰撞檢測
import pygame
import sys
white = (255, 255, 255)
black = ( 0, 0, 0)
# Player class
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load('../foo.png')
self.rect = self.image.get_rect()
class Rock(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load('../rock.png')
self.rect = self.image.get_rect()
self.rect.x = 50
self.rect.y = 50
# essential pygame init
pygame.init()
# screen
screen_width = 400
screen_height = 400
screen_size = (screen_width, screen_height)
screen = pygame.display.set_mode(screen_size)
# List for all sprites
sprites = pygame.sprite.Group()
# Rock
rock = Rock()
sprites.add(rock)
# Create player
player = Player()
sprites.add(player)
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
sys.exit()
sprites.update()
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT] and not player.rect.colliderect(rock.rect):
#if not player.rect.colliderect(rock.rect):
move = (-1, 0)
player.rect = player.rect.move(move)
if pressed[pygame.K_RIGHT] and not player.rect.colliderect(rock.rect):
move = (1, 0)
player.rect = player.rect.move(move)
if pressed[pygame.K_UP] and not player.rect.colliderect(rock.rect):
move = (0, -1)
player.rect = player.rect.move(move)
if pressed[pygame.K_DOWN] and not player.rect.colliderect(rock.rect):
move = (0, 1)
player.rect = player.rect.move(move)
screen.fill(white)
sprites.draw(screen)
pygame.display.flip()
clock.tick(30)
pygame.quit()
編輯:當我將移動速度降低到1時,玩家仍然卡在岩石中。我也更新了代碼。
現在我覺得很愚蠢......你是對的 –
@ Don'clickonmyprofile但是一旦你碰撞你已經在搖滾。這可能不是你想要的行爲,即使你稍後可以退出。 –