turtle.towards() function in Python

The turtle.towards() function in Python returns the angle between the line from the turtle’s position to (x, y) and the turtle’s start orientation. This is useful for pointing the turtle at a specific point.

Syntax: turtle.towards(x, y=None)
Parameters: x – a number or a coordinate pair (x, y); y – a number (if x is a number).

Let us see an example to implement the turtle.towards() function in Python:

Demo14.py

# turtle.towards() function in Python
# Code by Studyopedia

import turtle

window = turtle.Screen()
t = turtle.Turtle()

# Get the angle from turtle to point (100, 100)
angle = t.towards(100, 100)
print("Angle to point (100, 100):", angle)

t.goto(100, 100)  # Move to that point

window.exitonclick()

The following is the output:

turtle.towards() function in Python

In the above code, we followed the below steps:

  1. Import the module: import turtle loads Python’s turtle graphics library.
  2. Create the screen: window = turtle.Screen() opens the drawing window.
  3. Create the turtle: t = turtle.Turtle() creates the turtle you’ll control.
  4. Compute angle to a point: angle = t.towards(100, 100) calculates the absolute heading (in degrees) from the turtle’s current position to the point (100, 100). It does not move the turtle; headings are measured with 0° to the right (east) and increasing counterclockwise.
  5. Print the angle: print(“Angle to point (100, 100):”, angle) displays that computed heading in the console.
  6. Move to the point: t.goto(100, 100) moves the turtle directly to coordinates (100, 100), drawing a straight line if the pen is down (default).
  7. Close on click: window.exitonclick() keeps the window open until you click inside it, then closes.

If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Read More:

turtle.clearstamp() function in Python
turtle.heading() function in Python
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment