Checking the Sides of a Diagonal Line in Python
Consider the moving body (circle) from the previous demonstration (lesson).
We could put a straight diagonal line in front of the ball (circle)
and perform a certain action (like changing the colour of
the ball) just after the ball has crossed the diagonal line
moving from left to right.
Code to Detect Crossing (Trespass) over Straight Line Region in Python
To check for when our ball crosses the straight line,
we will continually check the x position (mid-point)
of the ball against the x position gotten using the
equation of the straight line at the same y position
to as that of the ball.
If we designate the coordinates of the ball as
(xb, yb), and those of
the line at the same height as the ball as
(xl, yl),
then,
xl = myd + c
Ball (mid-point) has crossed line when
xd >= xl.
Create a new file; File, New File.
Call it StraightLineRegion.py.
Type out the adjoining Pythonbody travel code for detecting the
instance a travelling body crosses the path of a straight line.
Python code for StraightLineRegion file
from Facet import Template
def prep():
global x_line, x_ball, y_ball
scene.button.onrelease(play)
screen.delay(20)
turtle.penup()
turtle.setposition(scene.button.xcor(), scene.button.ycor()-10)
turtle.pendown()
turtle.write("Move", align="center", font=("Arial",16,"bold"))
x1 = 0; y1 = scene.wnd_height/3
x2 = 200; y2 = -scene.wnd_height/3
m = (y2 - y1) / (x2 - x1)
c = (x2*y1 - x1*y2) / (x2 - x1)
diameter = 5
ball_colour = "#ffff00"
x_ball = 100 - scene.wnd_width/2; y_ball = 0
x_line = (y_ball - c) / m
turtle.penup()
turtle.setposition(x1, y1)
turtle.pendown()
turtle.setposition(x2, y2)
turtle.penup()
turtle.setposition(x_ball, y_ball)
turtle.setheading(0)
turtle.shape("turtle")
turtle.shapesize(diameter, diameter)
turtle.color(ball_colour, ball_colour)
def play(x, y):
global x_ball, y_ball, x_line
if x_ball < scene.wnd_width/2 - 10*turtle.shapesize()[1]:
ball_colour = "#ffff00"
if x_ball >= x_line:
ball_colour = "#00ff00"
turtle.color(ball_colour, ball_colour)
turtle.setposition(x_ball, y_ball)
x_ball += 10
screen.ontimer(play(0,0), 500)
else:
x_ball = 100 - scene.wnd_width/2; y_ball = 0
screen.mainloop()
scene = Template();
turtle = scene.controlButtons()
screen = scene.screen
prep()
Important: When trying to click on the button to get things
started, you might need to click away from the button text.