gpt4 book ai didi

python - Pygame 速度和碰撞问题

转载 作者:行者123 更新时间:2023-12-01 09:26:37 32 4
gpt4 key购买 nike

我目前正在为考试制作期末项目,并且正在制作一款平台游戏。事实上,我已经进行了碰撞并且它起作用了。但实际的问题是,如果我跳到平台上并且让玩家保持静止 1 秒,玩家就会消失,这很奇怪。你能帮我解决这个问题吗?我有一个提示,这个问题与速度有关(调用 vitesse_x 和 vitesse_y)。

import pygame
from pygame.locals import *
pygame.init()

fenetre = pygame.display.set_mode((1024,768))
pygame.display.set_caption("Portal Escape")

class Perso(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((50,50))
self.rect = self.image.get_rect(bottomleft=(0,740))
self.image.fill((255, 0, 0))
self.doit_monter = False
self.vitesse_x = 0
self.vitesse_y = 0

def update(self):
self.rect.x += self.vitesse_x
self.rect.y += self.vitesse_y
touche = pygame.key.get_pressed()
if touche[pygame.K_RIGHT] and self.rect.x < 920:
self.vitesse_x += 1
if touche[pygame.K_LEFT] and self.rect.x > 0:
self.vitesse_x -= 1
collision = pygame.sprite.spritecollide(self, blocs, False)
for bloc in collision:
if self.vitesse_y >= 0:
self.rect.bottom = bloc.rect.top
elif self.vitesse_y < 0:
self.rect.top = bloc.rect.bottom

perso = Perso()

class Bloc(pygame.sprite.Sprite): #pour creer un obstacle et éléments du jeu
def __init__(self, x, y, w, h):
super().__init__()
self.image = pygame.Surface((w,h))
self.image.fill((0, 255, 0))
self.rect = self.image.get_rect(topleft=(x, y))

all_sprites = pygame.sprite.Group()
blocs = pygame.sprite.Group()

all_sprites.add(perso)

b1 = Bloc(200,500,250,50)
b2 = Bloc(500,600,200,50)
b3 = Bloc(0,740,1024,30)
blocs.add(b1,b2,b3)
all_sprites.add(b1,b2,b3)

new_y = 0

continuer = True
while continuer:
pygame.time.Clock().tick(60)
for event in pygame.event.get():
if event.type == QUIT:
continuer = False
if event.type == KEYDOWN:
if event.key == pygame.K_SPACE:
perso.doit_monter = True
new_y = perso.rect.y - 100

if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT and perso.vitesse_x < 0:
perso.vitesse_x = 0
perso.vitesse_y = 0
if event.key == pygame.K_RIGHT and perso.vitesse_x > 0:
perso.vitesse_x = 0
perso.vitesse_y = 0
if event.key == pygame.K_SPACE and perso.vitesse_y < 0:
perso.vitesse_y = 0

if perso.doit_monter == True:
if perso.rect.y > new_y and perso.rect.y > 0:
perso.vitesse_y -= 5
else:
perso.doit_monter = False
else:
perso.vitesse_y += 1
all_sprites.update()

fenetre.fill((0,0,0))
all_sprites.draw(fenetre)
pygame.display.flip()

pygame.quit()

最佳答案

好吧,简单,问题,简单的解决方案。如果您在地面上,则必须重置 y 速度。

Person.update中:

    for bloc in collision:
if self.vitesse_y >= 0:
self.vitesse_y = 0 # reset velocity, so it isn't increasing forever
self.rect.bottom = bloc.rect.top
elif self.vitesse_y < 0:
self.rect.top = bloc.rect.bottom

如果你不这样做,速度将会增加,直到它足够高,可以一口气跳过地板而不会与停止框相撞

关于python - Pygame 速度和碰撞问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50336853/

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