How to get distance from a line

So I have a line in my code. And a object moves alongside it. How can I say that if the object more than 50 pixels away from the line, then move the object. If the object is less than 50 pixels away from the line, then move the object in the other direction?

I don’t need help on moving the object. I need help on the detection. Thank you.


Check out the distance function.


And here:

1 Like

Hi @Cybernet,

I think you are looking for the orthogonal projection of your object onto a line.

Note that:

  • the function introduced in the video returns a point location (the orthogonal projection). The distance between that point and your object corresponds to the distance between the line and your object.

  • this function assumes you’re looking for a projection onto a line (extending in the two directions, endlessly). If you are looking for the distance between an object and a segment (a portion of that line) you will need to constrain the dot product to not exceed the magnitude of that segment.

edit: don’t know how to embed properly ! (see original code/sketch here)


Thank you so much! This really help!

Great solution!

Just to be clear for everyone, hosts p5.js (JavaScript) sketches – so the solution is the same, but the code will be a bit different from Processing (Java mode).

1 Like

check the library Point2Line, it could be helpful for these kind of tasks