2

I'm playing around with movement in Turtle, I'm trying to get basic 2D WASD movement working; what I mean by consistent is the same speed, no lag spikes and/or random speed boosts. This is my current code: (I mapped the keys to a dict to prevent key press delay)

import turtle

keys = {
    "w": False,
    "s": False,
    "a": False,
    "d": False
}

turtle.setup(800, 590)

turtle.delay(0)
turtle.tracer(0, 0)

wn = turtle.Screen()

player = turtle.Turtle()
player.speed(4)

def movement():
    if keys["w"]:
        player.goto(player.xcor(), player.ycor() + 3)
    if keys["s"]:
        player.goto(player.xcor(), player.ycor() - 3)
    if keys["a"]:
        player.goto(player.xcor() - 3, player.ycor())
    if keys["d"]:
        player.goto(player.xcor() + 3, player.ycor())
    turtle.update()

def c_keys(key, value):
    keys[key] = value

wn.onkeypress(lambda: c_keys("w", True), "w")
wn.onkeyrelease(lambda: c_keys("w", False), "w")
wn.onkeypress(lambda: c_keys("s", True), "s")
wn.onkeyrelease(lambda: c_keys("s", False), "s")
wn.onkeypress(lambda: c_keys("a", True), "a")
wn.onkeyrelease(lambda: c_keys("a", False), "a")
wn.onkeypress(lambda: c_keys("d", True), "d")
wn.onkeyrelease(lambda: c_keys("d", False), "d")

wn.listen()

while True:
    movement()

Any help is appreciated, thanks!

bread
  • 160
  • 1
  • 10
  • Does this answer your question? [How to bind several key presses together in turtle graphics?](https://stackoverflow.com/questions/47879608/how-to-bind-several-key-presses-together-in-turtle-graphics) – ggorlen Jan 20 '23 at 16:25
  • @ggorlen no, I'm already doing that at the bottom. I want to know how to keep the movement the same speed with no lag. – bread Jan 20 '23 at 16:28
  • 1
    No, you're not. The key to keeping speed (fairly) consistent is `ontimer`, not `while: True`, which just slams the CPU as hard as it can. On my slow CPU, this shoots the turtle way off the screen immediately upon touching any WASD key. Beyond `ontimer`, getting a consistent framerate is [difficult, use-case dependent and probably out of scope for turtle](https://gafferongames.com/post/fix_your_timestep/). See also [How to fix inconsistent frame rate (speed) in python turtle](https://stackoverflow.com/a/55499265/6243352). – ggorlen Jan 20 '23 at 16:44
  • 1
    `ontimer` works, not exactly what I was going for, but it fixes the problem completely. Thanks! – bread Jan 20 '23 at 20:31

1 Answers1

0

(Thanks to ggorlen) The issue was the while True:. Using ontimer fixed the problem and made the movement stable and non laggy.

bread
  • 160
  • 1
  • 10