请帮忙。
我是pygame的新手。我无法理解为什么我的碰撞检测不起作用。我正在使用spritecollide,只是看不出为什么没有从sprites_list中删除sprite。我正在使用图像和pygame绘制的圆圈这可能与它有关吗?
游戏应该是一个非常简单的收集游戏,其中玩家精灵可以使用箭头键移动并导致红色圆圈消失。非常感谢您提供任何帮助。
import pygame, sys
from pygame.locals import *
import random
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("king_black.png")
self.rect = self.image.get_rect()
class CircleSprite(pygame.sprite.Sprite):
def __init__(self, colour, width, height):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([width, height])
self.rect = self.image.get_rect()
self.image.set_colorkey((0,0,0))
pygame.draw.ellipse(self.image, colour, [0, 0, width, height])
#initialise pygame
pygame.init()
#Setup game clock
FPS = 30 #Frames per second
clock = pygame.time.Clock()
#Setup display
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption("Hello world!")
#Setup colours
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
rect_x = 200
rect_y = 150
rect_width = 100
rect_height = 50
player = Player()
#Create a sprite group
sprites_list = pygame.sprite.Group()
#Circle list
circle_list = pygame.sprite.Group()
for i in range(10):
circle = CircleSprite(RED, 40, 40)
# Set a random location for the circle
circle.rect.x = random.randrange(400)
circle.rect.y = random.randrange(300)
# Add the circle to the list of objects
sprites_list.add(circle)
sprites_list.add(player)
#Main game loop
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
#Looks for pressed keys
keys_pressed = pygame.key.get_pressed()
#Responds to most recent key pressed
if keys_pressed[K_LEFT]:
rect_x -= 5
if keys_pressed[K_RIGHT]:
rect_x += 5
if keys_pressed[K_UP]:
rect_y -= 5
if keys_pressed[K_DOWN]:
rect_y += 5
#Collision detection
sprite_hits = pygame.sprite.spritecollide(player, sprites_list, True)
#Draw screen background
DISPLAYSURF.fill((WHITE))
#Draw circles to display
sprites_list.draw(DISPLAYSURF)
#Blit image to display and flip it.
DISPLAYSURF.blit(player.image, (rect_x, rect_y))
pygame.display.flip()
clock.tick(FPS)
答案 0 :(得分:0)
如果您打印播放器的矩形或在矩形(DISPLAYSURF.blit(player.image, player.rect)
)处显示图像,您将看到它永远不会移动并且只停留在默认坐标(0,0) 。由于rect
用于碰撞检测,因此玩家无法与圆形精灵碰撞。
您必须更新每个帧的矩形位置,或直接递增player.rect.x
和player.rect.y
。
if keys_pressed[K_LEFT]:
rect_x -= 5
if keys_pressed[K_RIGHT]:
rect_x += 5
if keys_pressed[K_UP]:
rect_y -= 5
if keys_pressed[K_DOWN]:
rect_y += 5
player.rect.topleft = (rect_x, rect_y)