Why is my player falling through the platform after the second collision?
I am currently trying to have my player fall when not on a platform, and have it not fall when on a platform. If I jump straight up, and land on the platform again (this would be the second collision), then my player falls through. How would I go about fixing this?
Code for reference:
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()
I think your problem lies there:
if herorect.colliderect(platform1rect) == True: herorect.move_ip(0,0)
Since the program works frame by frame, if the speed is too fast, the hero may "skip" the platform (at one iteration it is "over", at the other iteration it is "under"), therefore never colliding?
Try changing the condition to see if the Y coordinate is lower than the top of the platform.
Hope that helps.