Kevin Zheng
Kevin Zheng

Reputation: 1

Move Python Turtle horizontally without changing heading

I'm working on a game in Python-3 that requires moving a Turtle object horizontally (AKA sideways) without changing my heading. turtle.goto(x,y) or turtle.setx(x) turtle.sety(y) won't work because I want the object to show up when moving, just like when you do turtle.fd(distance).

Here is the code I have now:

import turtle 
turtle.speed('slowest')
turtle.lt(90)
turtle.fd(20)
turtle.rt(90)

With this code, the turtle turns, moves forward, and turns back. Is there a way I could move sideways without having to turn?

Thanks a lot! Any comments will be welcome!

Upvotes: 0

Views: 3182

Answers (1)

cdlane
cdlane

Reputation: 41872

turtle.goto(x,y) or turtle.setx(x) turtle.sety(y) won't work because I want the object to show up when moving

Your premise is false -- the turtle will show up when moving with all of these operations:

import turtle

turtle.speed('slowest')

turtle.sety(turtle.ycor() + 100)

turtle.done()

This moves the turtle vertically while maintaining a horizontal heading. It doesn't teleport, it's the same visible motion as a .forward()

However, if you have some other reason not to use goto(), setx(), sety(), etc. and want to use forward(), backward() instead, there's a way we can do this. The turtle cursor has a concept of tilt, allowing it to look in one direction while moving in another:

import turtle

turtle.speed('slowest')

turtle.tracer(False)  # hide the heading change ...
turtle.setheading(90)
turtle.settiltangle(-90)  # ... until we can tilt it
turtle.tracer(True)

turtle.forward(100)

turtle.done()

One situation where we might use this is a space invaders style game where the turtle wants to face towards the top of the window but we want to use forward() and backward() to control its motion side-to-side on the screen:

""" Oversimplified Example """

from turtle import Turtle, Screen

screen = Screen()

turtle = Turtle('turtle', visible=False)
turtle.settiltangle(90)
turtle.penup()
turtle.showturtle()

screen.onkey(lambda: turtle.forward(10), "Right")
screen.onkey(lambda: turtle.backward(10), "Left")

screen.listen()

screen.mainloop()

Upvotes: 2

Related Questions