0

I am making a platformer and am trying to make a player be able to stay on top of a platform. When I check if they are colliding, I check if the bottom of the player meets the top of the platform. It doesn't give an output, can someone please help?

The buggy part is the collisions where playerRect.colliderect(platform): and the bit below that as well. Help would be much appreciated.

import pygame

pygame.init()

screen = pygame.display.set_mode((1400, 900))

clock = pygame.time.Clock()

playerX = 700
playerY = 870

jumping = False
goingRight = False
goingLeft = False
jumpSpeed = 1
jumpHeight = 18
yVelocity = jumpHeight
gravity = 1

speed = 6

white = (255, 255, 255)
black = (0, 0, 0)

running = True
while running:

    screen.fill(black)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

    keys = pygame.key.get_pressed()

    if keys[pygame.K_SPACE]:
        jumping = True

    if keys[pygame.K_LEFT]:
        goingLeft = True

    if keys[pygame.K_RIGHT]:
        goingRight = True

    platform = pygame.draw.rect(screen, white, (100, 840, 100, 30))

    playerRect = pygame.draw.rect(screen, white, (playerX, playerY, 30, 30))

    if jumping:
        playerY -= yVelocity
        yVelocity -= gravity
        if yVelocity < -jumpHeight:
            jumping = False
            yVelocity = jumpHeight

    if goingLeft:
        playerX -= speed
    if goingRight:
        playerX += speed
    if event.type == pygame.KEYUP:
        if event.key == pygame.K_LEFT:
            goingLeft = False
        if event.key == pygame.K_RIGHT:
            goingRight = False

    if playerRect.colliderect(platform):
        if playerRect.bottom - platform.top == 0:
            playerRect.bottom = platform.y

    pygame.display.update()

    clock.tick(60)

`

Giltom09
  • 1
  • 1
  • What do you expect to happen when your check detects a collision? You change `playerRect`, but that does basically nothing since you store the player position in `playerX` and `playerY`, not in `playerRect`. My advise would to remove `playerX` and `playerY` and create `playerRect` once outside the loop. That would be a good start. – sloth Jan 31 '23 at 07:59
  • @sloth Then how would I change the x and y value – Giltom09 Jan 31 '23 at 08:20
  • Just use `playerRect`, it already contains a x and y property. Just use this. – sloth Jan 31 '23 at 09:29
  • @sloth It doesn't move now? – Giltom09 Jan 31 '23 at 09:35

1 Answers1

0

Most likely this part is the problem.

if playerRect.bottom - platform.top == 0:

You should check if bottom of the player is higher than the top of the platform since chance of them being exact is not high since your yVelocity is different than 1.

ertucode
  • 560
  • 2
  • 13