gpt4 book ai didi

python - 从 Pygame 中的一组中获取特定 Sprite

转载 作者:太空宇宙 更新时间:2023-11-04 00:14:26 26 4
gpt4 key购买 nike

我试图在碰撞组中找到某个 Sprite 。在这种情况下,我的代码会检查每个平台以查看玩家是否正在触摸它。如果玩家正在触摸平台,我希望玩家的底部 y 成为平台的(玩家正在触摸的)顶部 y。我不知道如何捕获某个平台,并编辑那个平台的属性。我将如何编辑我的代码以使其工作?

import pygame
import random

WIDTH = 500
HEIGHT = 400
FPS = 30

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

playerImage = "blockBandit/BlockBandit.png"

class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 50))
self.image = pygame.image.load(playerImage).convert()
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
self.vx = 0
self.vy = 0

class Platform(pygame.sprite.Sprite):
def __init__(self, x, y, w, h):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((w, h))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y

pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Block Bandit")
clock = pygame.time.Clock()

allPlatforms = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
player = Player()
p1 = Platform(0, HEIGHT - 40, WIDTH, 40)
all_sprites.add(p1)
allPlatforms.add(p1)
all_sprites.add(player)


def moveCharacter(object):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
object.vx += -2
if keys[pygame.K_RIGHT]:
object.vx += 2
if keys[pygame.K_UP]:
object.vy -= 12
pygame.quit()

object.vx = object.vx * 0.9

if abs(object.vx) < 1:
object.vx = 0

if abs(object.vx) > 10:
if object.vx < 0:
object.vx = -10
else:
object.vx = 10

object.vy = object.vy + 1
object.rect.x += object.vx
object.rect.y += object.vy

hits = pygame.sprite.spritecollide(object, allPlatforms, False)
if hits:
# object.rect.y = hits[0].rect.midbottom
object.rect.y -= 1
object.vy = 0
if object.rect.bottom < allPlatforms.top:
object.rect.y = allPlatforms.top
print(object.rect.midbottom)

running = True

while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

moveCharacter(player)
# Update State
all_sprites.update()

# Render
screen.fill(BLACK)
all_sprites.draw(screen)

# screen.blit(player.icon, (20, 40))
pygame.display.flip()

pygame.quit()

最佳答案

hits 是碰撞平台 Sprite 的列表,因此您可以使用 for 循环对其进行迭代并设置 object.rect.bottomplatform.rect.top

hits = pygame.sprite.spritecollide(object, allPlatforms, False)
for platform in hits:
object.vy = 0
object.rect.bottom = platform.rect.top

关于python - 从 Pygame 中的一组中获取特定 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51426583/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com