Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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 playery increments by one at every iteration 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 playery 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.

share|improve this question

1 Answer 1

up vote 4 down vote accepted
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

I'm pretty sure this is where the problem lies. Taking the first one for example, you're saying that if the left key is not pressed and the player is moving in an x direction, increase the x.

Change the abs(playerx) > 0 to playerx < 0 and the following lines would be playerx > 0, playery < 0, and playery > 0, respectively.

Hope that does it!

share|improve this answer
    
Works! Thanks a bunch. So the problem was that one of both my expressions was true due to the fact that if I press left, right is obviously false and so on. So it kept incrementing. I should have seen this... –  Dominic Grenier Mar 24 '12 at 4:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.