Moving turtle with mouse demands pointer detection. To do that we will use onscreenclick() method. As argument we will use our custom method that will print those coordinates inside Python Shell window:
from turtle import *
t = Turtle()
def get_coords(x, y):
print(x, y)
onscreenclick(get_coords)
Once we have pointer coordinates we will push turtle object to those new positions using goto() method:
from turtle import *
t = Turtle()
def get_coords(x, y):
t.goto(x, y)
onscreenclick(get_coords)
Just for fun we will change turtle object shapesize.
Also we have problem because arrow (turtle object) is always oriented to right side. Arrow will still follow mouse when we add new line inside custom function:
t.setheading(t.towards(x, y))
We are trying to set new heading to where object is oriented. But problem remains for now. This is full source:
from turtle import *
t = Turtle()
t.shapesize(10, 10, 10)
def get_coords(x, y):
t.goto(x, y)
t.setheading(t.towards(x, y))
onscreenclick(get_coords)
Solution is simple. We need to change order of lines in custom function, like this:
def get_coords(x, y):
t.setheading(t.towards(x, y))
t.goto(x, y)
Now our turtle object will rotate and travel in same direction:
from turtle import *
t = Turtle()
t.shapesize(10, 10, 10)
t.speed(0)
t.color("red")
def get_coords(x, y):
t.setheading(t.towards(x, y))
t.goto(x, y)
onscreenclick(get_coords)
You are definitely advised to check YouTube tutorial on How to move Turtle with Mouse.
No comments:
Post a Comment