为什么我的播放器在第二次碰撞后从平台上掉下来?

2024-04-18 05:39:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正试图让我的球员下跌时,不在一个平台上,并没有下跌时,在一个平台上。如果我直接跳起来,再次降落在平台上(这将是第二次碰撞),那么我的球员就会摔倒。 我该怎么解决这个问题?你知道吗

参考代码:

import pygame,sys,random
import time
global currentpos
global velocity
velocity = 20
allowjump = True

clock = pygame.time.Clock()
fps = 60
playerspeed = 6
velocity = 28
ljump = False
rjump = False
pygame.init()
from pygame.locals import *
jumping = False
screen = pygame.display.set_mode((1200,720))
hero = pygame.image.load('hero.png')
platform1 = pygame.image.load('platform.png')
herorect = hero.get_rect(top = 401,left = 20)
platform1rect = platform1.get_rect(top = 425,left = 20)
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((40,133,255))
interjump = False
fallvelocity = -.5
while True:
        clock.tick(fps)


        screen.blit(background ,(0,0))
        screen.blit(hero, herorect)
        screen.blit(platform1, platform1rect)
        if pygame.key.get_pressed()[pygame.K_LEFT] == True:

                herorect.move_ip(-playerspeed,0)

        elif pygame.key.get_pressed()[pygame.K_RIGHT] == True:
                herorect.move_ip(playerspeed,0)

        for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                        if event.key == K_SPACE and allowjump == True:
                                jumping = True
                if event.type == pygame.KEYUP:
                        if event.key == K_SPACE and allowjump == False:
                                interjump = True


                if event.type == pygame.QUIT:

                        pygame.quit()
                        sys.exit()
        if herorect.colliderect(platform1rect) == True:
                herorect.move_ip(0,0)


        elif herorect.colliderect(platform1rect) == False:

                herorect.move_ip(0,fallvelocity)
                fallvelocity += .5



        if jumping == True:
                allowjump = False
                herorect.move_ip(0,-velocity)
                velocity -= 1

        if velocity == -29:
                jumping = False
                allowjump = True
                velocity = 28


        pygame.display.update()

Tags: ipeventfalsetruegetmoveifscreen
1条回答
网友
1楼 · 发布于 2024-04-18 05:39:01

我认为你的问题在于:

if herorect.colliderect(platform1rect) == True:
            herorect.move_ip(0,0)

由于程序是逐帧运行的,如果速度太快,英雄可能会“跳过”平台(在一次迭代中它是“结束”,在另一次迭代中它是“下”),因此永远不会碰撞?你知道吗

尝试更改条件以查看Y坐标是否低于平台顶部。你知道吗

希望有帮助。你知道吗

相关问题 更多 >