我目前正试图让我的播放器在不在平台上时摔倒,并且在平台上时它不会掉落。如果我直接跳起来,再次降落在平台上(这将是第二次碰撞),那么我的玩家就会失败。 我该如何解决这个问题?
参考代码:
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()
答案 0 :(得分:0)
我认为你的问题就在那里:
if herorect.colliderect(platform1rect) == True:
herorect.move_ip(0,0)
由于程序逐帧工作,如果速度太快,英雄可能会“跳过”平台(在一次迭代时它“超过”,在另一次迭代时它“在”下面),因此从不碰撞?
尝试更改条件以查看Y坐标是否低于平台顶部。
希望有所帮助。