anyone got an idea for point in triangle code?

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

Post Reply
User avatar
avansc
Respected Programmer
Respected Programmer
Posts: 1708
Joined: Sun Nov 02, 2008 6:29 pm

anyone got an idea for point in triangle code?

Post by avansc »

i know there are probably hundreds of articles online, but sometimes its just better to try on your own.

i came up with this idea (though im sure it was thought of 100's of years ago by someone with a funny last name)
you have the normals of each line, and if the point to the normal vector and the normal vector have a angle greater than 90 degrees between them they point is out side of the triangle. this method is computation heavy so if anyone had other ideas let me know.

this algo can be sped up quite alot by tabulating the trig functions.

Image
Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
User avatar
avansc
Respected Programmer
Respected Programmer
Posts: 1708
Joined: Sun Nov 02, 2008 6:29 pm

Re: anyone got an idea for point in triangle code?

Post by avansc »

you could also see if the point lies in between pie slices <ACB and <CAB, if both are true then the point is in the triangle.
Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
User avatar
cypher1554R
Chaos Rift Demigod
Chaos Rift Demigod
Posts: 1124
Joined: Sun Jun 22, 2008 5:06 pm

Re: anyone got an idea for point in triangle code?

Post by cypher1554R »

What about the point to polygon method I used..? The one with vector cross product checking? http://elysianshadows.com/phpBB3/viewto ... art=999999

It can also be used for triangles (because it works for any convex polygon).
User avatar
avansc
Respected Programmer
Respected Programmer
Posts: 1708
Joined: Sun Nov 02, 2008 6:29 pm

Re: anyone got an idea for point in triangle code?

Post by avansc »

Code: Select all

    int side_of_line(Vec2 &a, Vec2 &b, Vec2 &p)
    {
       return float(p.y - a.y) * float(b.x - a.x) - float(p.x - a.x) * float(b.y - a.y);
    }

    bool point_inside_poly(std::vector<Vec2> &poly, Vec2 &point)
    {
       for(int i = 0; i < poly.size()-1; i++)
       {
          if(side_of_line(poly[i], poly[i+1], point) > 0)
             return false;

       }
       if(side_of_line(poly[poly.size()-1], poly[0], point) > 0)
             return false;
       return true;
    }

Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
Post Reply