Test if a point is between 2 points?
-
Is there a text built in to check if a point is between 2 other points? I know you can test if it is on a line, but that doesn't guarantee its between any 2 points, just that is it on the same lines as them.
I wrote something that I think is working, but I'd rather use a built in method if it exists.
Chris
-
When you say 'between' do you mean like this?
-
No, I mean if is co-linear and lies between them So like how to determine if a given point is on a given SketchUp Edge. And I think I got a working method, but it might be returning false positives, or rather false negatives. So I might have a typo or my math might be bad or it mgiht be that I"m not feeding it the points I tihnk I am. Do you have any math-y tricks for testing this?
Chris
-
Chris,
You can take inspiration of the following:
#Check if a point is within a segment defined by 2 points. Return true or false def is_within_seg?(pt, pt1, pt2) return false unless pt && pt1 && pt2 return true if pt == pt1 || pt == pt2 return false unless pt.on_line?([pt1, pt2]) pt1.vector_to(pt) % pt2.vector_to(pt) < 0 end
Basically, you check that the point is on the line, and then that the 2 vectors joining it to the 2 points are opposite.
Fredo
-
All right! That took a lot thinking to comprehend all that, but yes, that does exactly what I had in mind, and is significantly shorter (+/-30 lines!). Thanks so much Fredo!
Chris
-
It's also much faster.
As a general rule of thumb, it is better to used geometric primitives of the Sketchup API (written in compiled C behind the scene) than to do our own calculations on coordinates in Ruby (interpreted). -
Very good to know. I've never tested anything like that, but I had a suspicion that it is true. Thanks for thiking of a method that uses SU native natives. Mine involved an algebraic formula being applied to each x,y,z coordinate, and if it got fed zero's would return NaN or Infinity, so I also had to teste everynumber before it passed through. In the end, it was quite long and I'm sure it was slow.
I've got it set up where I could do a time test on it, Id be interested in seeing how much faster it is.
Thanks Fredo!
Chris
Advertisement