turtle.towards() function in Python
turtle.towards() returns the angle (in degrees) from the turtleâs current position to a target point (x, y), measured counterclockwise from the east (0°). It does not move the turtle, only calculates the direction.
Syntax:
turtle.towards(x, y=None)
Parameters:
- x: Single number (with y), point (x, y), or another turtle.
- y: Number if x is single; else None.
Examples
Example 1: Basic Directions
import turtle
ang = turtle.towards(100, 0)
print(ang)
ang = turtle.towards(0, 100)
print(ang)
ang = turtle.towards(-100, 0)
print(ang)
ang = turtle.towards(0, -100)
print(ang)
Output :
0.0
90.0
180.0
270.0
Example 2: Towards a Point
import turtle
ang = turtle.towards(50, 50)
print(ang)
ang = turtle.towards(-50, 50)
print(ang)
ang = turtle.towards(-50, -50)
print(ang)
ang = turtle.towards(50, -50)
print(ang)
Output:
45.0
135.0
25.0
315.0
Example 3: Using Another Turtle
import turtle
t1 = turtle.Turtle()
t2 = turtle.Turtle()
t2.setpos(100, 100)
ang = t1.towards(t2)
print(ang)
Output
45.0
Explanation:
- Turtle t1 is at (0,0) by default.
- Turtle t2 is at (100,100).
- The angle from t1 â t2 is 45° (diagonal northeast).