python Velocity control of the player, why doesn't this work?

Posted by Dominic Grenier on Game Development See other posts from Game Development or by Dominic Grenier
Published on 2012-03-24T03:27:57Z Indexed on 2012/03/24 5:40 UTC
Read the original article Hit count: 365

Filed under:
|

I have the following code inside a while True loop:

if abs(playerx) < MAXSPEED:
    if moveLeft:
        playerx -= 1
    if moveRight:
        playerx += 1

if abs(playery) < MAXSPEED:
    if moveDown:
        playery += 1
    if moveUp:
        playery -= 1

if moveLeft == False and abs(playerx) > 0:
    playerx += 1
if moveRight == False and abs(playerx) > 0:
    playerx -= 1
if moveUp == False and abs(playery) > 0:
    playery += 1 
if moveDown == False and abs(playery) > 0:
    playery -= 1

player.x += playerx
player.y += playery

if player.left < 0 or player.right > 1000:
    player.x -= playerx
if player.top < 0 or player.bottom > 600:
    player.y -= playery

The intended result is that while an arrow key is pressed, playerx or y increments by one at every loop until it reaches MAXSPEED and stays at MAXSPEED. And that when the player stops pressing that arrow key, his speed decreases. Until it reaches 0. To me, this code explicitly says that...

But what actually happens is that playerx or y keeps incrementing regardless of MAXSPEED and continues moving even after the player stops pressing the arrow key.

I keep rereading but I'm completely baffled by this weird behavior. Any insights? Thanks.

© Game Development or respective owner

Related posts about 2d

Related posts about python