patterncsharpModerate
Point inside Polygon check
Viewed 0 times
insidecheckpolygonpoint
Problem
I have written a method to determine whether a Vector2 lies inside a polygon or outside of it. The polygon is defined by an array of clockwise vertices, p[]. It returns true if the point is inside, false otherwise.
It is perfectly functional, works with all edge cases, and is blazing fast. I want to know how I could make the method look prettier, and have better 'coding practices' though.
public bool polyCheck(Vector2 v, Vector2[] p)
{
int j = p.Length-1;
bool c = false;
for(int i=0;iv.y^p[j].y>v.y&&v.x<(p[j].x-p[i].x)*(v.y-p[i].y)/(p[j].y-p[i].y)+p[i].x;
return c;
}It is perfectly functional, works with all edge cases, and is blazing fast. I want to know how I could make the method look prettier, and have better 'coding practices' though.
Solution
I want to know how I could make the method look prettier, and have better 'coding practices' though
-
avoid single letter variable if they aren't iterator variables. If you or Sam the maintainer needs to come back to this method in a few months, neither you nor Sam will grasp at first glance what the variables are about.
-
avoid shortening of method names.
-
always use braces
-
let your variables and operators have some space to breathe. This
is just not readable.
-
avoid single letter variable if they aren't iterator variables. If you or Sam the maintainer needs to come back to this method in a few months, neither you nor Sam will grasp at first glance what the variables are about.
-
avoid shortening of method names.
polyCheck does not tell anything about what the method tries to do. A name like IsInPolygon would be better. With a more OO approach by adding a Polygon class having a method Contains(Vector2) it would be more clear. public class Polygon
{
public Vector2[] Vertices { get; private set; }
public Polygon(Vector2[] vertices)
{
Vertices = vertices;
}
public bool ContainsVector(Vector2 vector)
{
// do the magic
return true;
}
}-
always use braces
{} although they are optional for single lined for's. This will help you to make your code less error prone. -
let your variables and operators have some space to breathe. This
c^=p[i].y>v.y^p[j].y>v.y&&v.x<(p[j].x-p[i].x)*(v.y-p[i].y)/(p[j].y-p[i].y)+p[i].x;is just not readable.
Code Snippets
public class Polygon
{
public Vector2[] Vertices { get; private set; }
public Polygon(Vector2[] vertices)
{
Vertices = vertices;
}
public bool ContainsVector(Vector2 vector)
{
// do the magic
return true;
}
}c^=p[i].y>v.y^p[j].y>v.y&&v.x<(p[j].x-p[i].x)*(v.y-p[i].y)/(p[j].y-p[i].y)+p[i].x;Context
StackExchange Code Review Q#108857, answer score: 11
Revisions (0)
No revisions yet.