How to find point of intersection with vectors

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By rayohvv

Let’s say I have a 2d ball going in a certain direction, how do I know at what position it will be when it’s y position will be at 40, so it intersects the function y=40.

Is there an easy way to do this with a Vector2 method?

:bust_in_silhouette: Reply From: haydenv

One option is to put an if-statement in the _process function of a script attached to the ball.

if abs(position.y - 40) < 0.001:
    print("position of ball when near the line y=40: " + str(position))

Another option is to make an Area2D node (named, say, ThinRectangle), and make a thin rectangular CollisionShape2D as a child of ThinRectangle, and position it on the line y=40. Then connect ThinRectangle’s area_entered or body_entered signal to the function you want to call whenever the ball enters that thin rectangle. If the ball has a RigidBody2D node, then you’d connect the ThinRectangle’s body_entered signal. Otherwise, if the ball has an Area2D node instead of a RigidBody2D node, then you’d connect ThinRectangle’s area_entered signal. Let’s say the ball has a RigidBody2D, so you connect ThinRectangle’s body_entered signal to a function on the ball named _on_body_entered. Then your code might look something like

_on_thin_rectangle_body_entered(body: Node2D):
    print("position of ball when near the line y=40: " + str(position))

I would recommend doing the second way. The first way is simpler, but it has an issue when the ball is moving quickly. If the ball is moving so fast that it shoots past the line y=40 in one frame, then the ball’s position.y might never be within 0.001 of the line y=40. But if you use the second way you are using the physics system, and the physics system is able to automatically figure out if a fast moving object moved through the ThinRectangle or not.

May anyone please feel free to ask for further clarification, to make corrections, or to add to my answer.

:bust_in_silhouette: Reply From: jgodfrey

There’s also a line_intersects_line() method that could be useful if you simply want to calculate if and where an intersection exists…