I am new to creating games with graphics, and I want to make a very hard game. I have the movement down, but it has a weird bug where it if the user presses down the opposing movement key (i.e. A is to go left and D is to go right), it goes in the opposite direction and when the user stops pressing the opposing key in question, they stop moving in either direction.
I have did research to try to solve this problem myself, and found this question on Stack Overflow, and it made sense, but when I tried it, just made it even worse.
How can I stop the player from moving if the opposing key is pressed at the same time?
Code
Original Code
while True:
if player.canMove:
if e.type == KEYDOWN:
if pressed[K_w] and not pressed[K_s]:
dy = -player.speed
if pressed[K_a] and not pressed[K_d]:
dx = -player.speed
if pressed[K_s] and not pressed[K_w]:
dy = player.speed
if pressed[K_d] and not pressed[K_a]:
dx = player.speed
elif e.type == KEYUP:
if e.key == K_c or e.type == QUIT:
close()
if e.key == K_a:
dx = 0
elif e.key == K_d:
dx = 0
elif e.key == K_w:
dy = 0
elif e.key == K_s:
dy = 0
Modified Code
while True:
up = None
left = None
down = None
right = None
if player.canMove:
if e.type == KEYDOWN:
up = pressed[K_w]
left = pressed[K_a]
down = pressed[K_s]
right = pressed[K_d]
dx += (right - left) * player.speed
dy += (down - up) * player.speed
elif e.type == KEYUP:
if e.key == K_c or e.type == QUIT:
close()
if e.key == K_a:
dx = 0
elif e.key == K_d:
dx = 0
elif e.key == K_w:
dy = 0
elif e.key == K_s:
dy = 0
```
up = pressed[K_w]
is equivalent to your linked question's answer ofpressed[pygame.K_w]
? \$\endgroup\$