• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Euronomus

closest point on a line

8 posts in this topic

I'm trying to find how, given a line and a point, to find the closest point on the line to that point. I searched around and could'nt find a standard way, so I've written a function using Bresenhams line alogorithm. I iterate through all the points in the line checking the distance for each point and when the current distance is greater than the previous I return the previous point. It works for most cases but not all and at this point I think I've just been staring at it for to long, so I was hoping someone could point out my problem or point me to a more consice method. this works line = 299, 200, 300, 300 point = 345, 400 this does'nt line = 300, 200, 300, 300 point = 345, 400
import math

def find_closest(line, point):
    x0, y0, x1, y1 = line
    x2, y2 = point
    steep = abs(y1-y0) > abs(x1-x0)
    if steep:
        x0,y0 = y0,x0
        x1,y1 = y1,x1
    if x0 > x1:
        x0,x1 = y1,x0
        y0,y1 = y1,y0
    deltax = x1-y0
    deltay = abs(y1-y0)
    err = 0
    if y0 < y1:
        ystep = 1
    else:
        ystep = -1
    y = x0
    old = None
    for x in range(x0, x1):
        if steep:
            d = math.sqrt(math.pow((y-y2),2)+math.pow((x-x2), 2))
            if old is None:
                old = (d, (y, x))
            elif d > old[0]:
                return old[1]
            old = (d, (y, x))
        else:
            d = math.sqrt(math.pow((x-x2),2)+math.pow((y-y2), 2))
            if old is None:
                 old = (d, (x, y))
            elif d > old[0]:
                return old[1]
            old =  (d, (x, y))
        err += deltay
        if err*2 > deltax:
            y += ystep
            err -= deltax
    return old[1]
if __name__ == '__main__':
    import Tkinter
    class Test(Tkinter.Frame):
        def __init__(self):
            Tkinter.Frame.__init__(self)
            self.grid()
            self.canv = Tkinter.Canvas(self, height=450, width=450, bg='white')
            self.line = Tkinter.Entry(self)
            self.point = Tkinter.Entry(self)
            self.gobutton = Tkinter.Button(self, text='go', command=self.run)
            self.canv.grid(row=0, column=0, columnspan=3)
            self.line.grid(row=1, column=0)
            self.point.grid(row=1, column=1)
            self.gobutton.grid(row=1, column=2)
            self.line.insert('end', '300, 200, 300, 300')
            self.point.insert('end', '345, 400')
        def run(self):
            line = [int(a) for a in self.line.get().split(',')]
            point = [int(a) for a in self.point.get().split(',')]
            x0, y0, x1, y1 = line
            x2, y2 = point
            x3, y3 = find_closest(line, point)
            self.canv.delete('all')
            self.canv.create_line(x0, y0, x1, y1, fill='red')
            self.canv.create_line(x2, y2, x3, y3, fill='blue')
    t = Test()
    t.mainloop()
[source\]
0

Share this post


Link to post
Share on other sites
it's simpler than that.

Line going through segment[A, B]
point P.

in pseudo code.


Vector GetClosetPoint(Vector A, Vector B, Vector P, bool segmentClamp)
{
Vector AP = P - A:
Vector AB = B - A;
float ab2 = AB.x*AB.x + AB.y*AB.y;
float ap_ab = AP.x*AB.x + AP.y*AB.y;
float t = ap_ab / ab2;
if (segmentClamp)
{
if (t < 0.0f) t = 0.0f;
else if (t > 1.0f) t = 1.0f;
}
Vector Closest = A + AB * t;
return Closest;
}




set 'segmentClamp' to true if you want the closest point on the segment, not just the line.
1

Share this post


Link to post
Share on other sites
Thank you, the whole time I was messing with this I kept thinking there had to
be an easier way but all my googling turned up nothing.
0

Share this post


Link to post
Share on other sites
For this you need to know about the dot product. Write the line in "ray" form: A point on the line can be expressed as P+t*v, where P is a point in the line, t is a real number and v is a vector along the direction of the line.

If your point is X, you want to minimize
dist(P+t*v , X) = (P+t*v-X).(P+t*v-X) = (P-X + t*v).(P-X + t*v) = (P-X).(P-X) + 2*t*(P-X).(v) + t^2*(v).(v)

If you plot that as a function of t, you get a parabola that achieves its minimum at t=-((P-X).(v))/((v).v()). This can be rewritten as ((X-P).(v))/((v).(v))

Your answer is P+((X-P).(v))/((v).(v))*v

0

Share this post


Link to post
Share on other sites
Quote:
Original post by Euronomus
I iterate through all the points in the line checking the distance
for each point and when the current distance is greater than the previous
I return the previous point. It works for most cases but not all and
at this point I think I've just been staring at it for to long, so I was
hoping someone could point out my problem or point me to a more consice method.


http://www.geometryalgorithms.com/

Look at this site, they have also other quite important algorithms.
0

Share this post


Link to post
Share on other sites
Simpler still? For a normalised ray about the origin, the answer is

min_dist = |ray × point|

That's the modulus of a vector cross-product if it's not clear. Turning an arbitrary line into such a ray is trivial, but I can't think of a way to restrict the line to a segment without losing out to oliii's method.

Edit: I get it now. This is just the distance to the closest point, whereas we need the point itself [pig].

Admiral

[Edited by - TheAdmiral on April 18, 2007 6:59:59 AM]
0

Share this post


Link to post
Share on other sites
Note that you will be working with floating point values. Especially for 't'. It's near the range [0, 1] usually.

If you are using ints, you'll need to do some clever shifting, so yuo can get a decent precision.
0

Share this post


Link to post
Share on other sites
Wouldn't the cloest point on the line be when the vector from the point on the line to your point in space is perpenciular to the line?

. is dot product

So if your line was [-1,3] + k[2,6] and point [5,4]

[2,6] . [5-(-1+2k),4-(3+6k)] = 0
[2,6] . [6 - 2k, 1 - 6k] = 0
12 - 4k + 6 -36k = 0
-40k = -18
k = 0.45

[-1 + 0.9, 3 + 2.7]
[-0.1,5.7] is your point
0

Share this post


Link to post
Share on other sites
Quote:
Original post by oliii
Vector GetClosetPoint(Vector A, Vector B, Vector P, bool segmentClamp)

But what if the point isn't in the closet, or doesn't want to come out [wink]

Here's my solution:
Vector GetClosestPoint(Vector A, Vector B, Vector P, bool segmentClamp)
{
float min_x = 0.0f, max_x = 0.0f;

for(float y = -3.40282e038; y <= 3.40282e038; y += 1.19209e-007)
for(float x = -3.40282e038; x <= 3.40282e038; x += 1.19209e-007)
if(point_on_line(A, B, Vector(x,y), segmentClamp))
if(length(Vector(x,y) - P) < length(Vector(min_x,min_y) - P))
{
min_x = x;
min_y = y;
}

return Vector(min_x,min_y);
}


[totally]

</hilarity>

In all seriousness though, the projection method is going to be your best bet. A direct algebraic method based on the dot product works too, but a lot better on paper than in code. As a matter of fact, the projection method might be better on paper too [smile]
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0