How to get the position of the turtle?
Asked Answered
H

4

8

How can I find the coordinate of a turtle in python?

For example, if the turtle is located at (200, 300), how would I retrieve that position?

Hifalutin answered 14/7, 2017 at 8:4 Comment(2)
fx = food.getx() AttributeError: 'Turtle' object has no attribute 'getx' I get this errorHifalutin
To access just the X (or Y) coordinate, you can use fx = food.xcor() (or food.ycor()) But best to work with food.getposition() (or its synonymfood.getpos()) if you need both coordinates.Glynas
C
9

As shown in the Python documentation, turtle.pos() returns the turtle’s current location as a 2D vector of (x,y).

Consumerism answered 5/2, 2018 at 4:3 Comment(0)
H
4

The turtle documentation says that turtle.pos() gets the position as a Vec2D vector.

Hoick answered 14/7, 2017 at 8:7 Comment(2)
so if I wanted to know if turtle1 and turtle2 were on the same coordinate I would do if turtle1.pos() == turtle2.pos()Hifalutin
@Hifalutin you would simply check if the Vec2D objects are equal, so yesHoick
G
2

I wanted to know if turtle1 and turtle2 were on the same coordinate I would do if turtle1.pos() == turtle2.pos()

Yes, but since the turtle plays on a floating point plane, this might cause you trouble when they are close but not exactly atop each other. You'll probably be better off with a test like:

turtle1.distance(turtle2) < 0.1

I.e. is the distance between centers less than some fuzz factor that you determine. If you want to know if any turtle parts overlap (e.g. legs touching) then your fuzz factor may be as high as 10.0

Glynas answered 14/7, 2017 at 17:48 Comment(0)
B
0

Well the turtle.pos() method returns a tuple

A Vector is derived from tuple, so a vector is a tuple!

so you can check if the turtle is at a specific coordinate by using:

if turtle.pos() == (5.0, 0.0):
    print(“at coordinate”)
Brusa answered 4/8, 2020 at 9:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.