user3458038
user3458038

Reputation: 5

My sprite keeps moving off of the screen in pygame

so I've been messing around with sprites and movement in pygame and the issue I keep running into with my code is that when you hold down the key the sprite won't stop moving, but if it is past the point at which it is supposed to stop and you let go and try again it will do what it is meant to and not move, is there any way I can have it happen straight away so it won't keep disappearing from my screen?

    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_RIGHT:
            if player.x + 4 < 700:
            moveX = 4
        else:
            moveX = 0
        if event.key == pygame.K_LEFT:
            if player.x == 0:
            moveX = 0
        else:
            moveX = -4
        if event.key == pygame.K_UP:
            moveY = -4


    if event.type == pygame.KEYUP:
        if event.key == pygame.K_RIGHT:
            moveX = 0
        if event.key == pygame.K_LEFT:
        moveX = 0
        if event.key == pygame.K_UP:
        moveY = 0
        player.falling = True
            player.collision = False
        player.onground = False

Upvotes: 0

Views: 508

Answers (1)

ssm
ssm

Reputation: 5373

Something seems not right with the indentation.

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_RIGHT:
        if player.x + 4 < 700:
        moveX = 4   # <----- should this be here ?
    else:           # <----- this should match the `event.key == pygame.K_RIGHT` condition
        moveX = 0
    if event.key == pygame.K_LEFT:
        if player.x == 0:
        moveX = 0
    else:
        moveX = -4
    if event.key == pygame.K_UP:
        moveY = -4

Can you please redo the indentation and check?

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_RIGHT:
        if player.x + 4 < 700: moveX = 4
        else:                  moveX = 0
    if event.key == pygame.K_LEFT:
        if player.x == 0:      moveX = 0 # here you might want to try player.x <= 0 ...
        else:                  moveX = -4
   ...

may be easier to handle ...

Upvotes: 1

Related Questions