【发布时间】:2020-06-08 22:36:28
【问题描述】:
嘿,我的游戏代码有问题。有没有办法检查,例如,我的玩家精灵(英雄)的右侧是否与组障碍精灵发生碰撞?
我只能弄清楚如何检查碰撞,但如果玩家的右侧与障碍物发生碰撞,我只想要一个真实的输出。
在我的代码中,我使用了一个不可见的精灵作为碰撞箱,并将玩家绘制在这个不可见的精灵中以检查碰撞,但让它看起来像是障碍物拒绝了玩家的移动。
import pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
PINK = (230, 77, 149)
FPS = 60
window_width = 900
window_height = 600
window_color = WHITE
window = pygame.display.set_mode((window_width, window_height))
window.fill(window_color)
pygame.display.set_caption("Bub - the game")
clock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, velocity, color):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((width + 2*velocity, height + 2*velocity))
self.rect = self.image.get_rect()
self.rect.topleft = (x - velocity, y - velocity)
self.velocity = velocity
self.is_jump = False
self.jump_count = 15
self.fall_count = 1
self.ground = self.rect.bottom
self.body = pygame.Rect(x, y, width, height)
pygame.draw.rect(window, color, self.body)
def move(self):
key = pygame.key.get_pressed()
if key[pygame.K_a] and self.rect.left >= 0:
self.rect.x -= self.velocity
if key[pygame.K_d] and self.rect.right <= window_width:
self.rect.x += self.velocity
if not self.is_jump:
if key[pygame.K_SPACE] and self.rect.bottom == self.ground:
self.is_jump = True
else:
if self.jump_count >= 0:
self.rect.y -= round((self.jump_count ** 2) * 0.1)
self.jump_count -= 1
else:
self.jump_count = 15
self.is_jump = False
def gravity(self):
if not self.is_jump and self.rect.bottom != self.ground:
self.rect.y += round((self.fall_count ** 2) * 0.1)
if self.fall_count <= 15:
self.fall_count += 1
else:
self.fall_count = 1
def update(self):
self.move()
self.gravity()
pygame.draw.rect(window, BLACK, self.body)
self.body.topleft = (self.rect.x + self.velocity, self.rect.y + self.velocity)
class Obstacle(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, color):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((width, height))
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.center = (x, y)
player_sprite = pygame.sprite.Group()
obstacle_sprite = pygame.sprite.Group()
hero = Player(0, 570, 30, 30, 5, BLACK)
player_sprite.add(hero)
obstacle_1 = Obstacle(100, 585, 120, 30, PINK)
obstacle_sprite.add(obstacle_1)
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill(window_color)
player_sprite.update()
player_sprite.draw(window)
obstacle_sprite.update()
obstacle_sprite.draw(window)
pygame.display.update()
pygame.quit()
【问题讨论】:
-
这听起来很简单,但“侧面碰撞”的真正含义是什么? 整个方面?这很容易。但是如果只有 5 个像素的边重叠呢?这还是重叠吗?当只有单个右上角像素重叠时怎么办?右上角的 3 个像素呢……这与顶部重叠太右了?
-
无论如何,一个快速简单的检查是:一旦检测到碰撞,检查右上角和右下角的像素是否都在碰撞。
标签: python python-3.x pygame sprite collision-detection