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.

Hello!

Check out the distance function.

Here:
https://processing.org/reference/dist_.html

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)

2 Likes

Thank you so much! This really help!

Great solution!

Just to be clear for everyone, editor.p5js.org 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