Draw a equilateral triangle given the center

Gautam picture Gautam · Jul 12, 2012 · Viewed 14.9k times · Source

How do I draw an equilateral triangle given the center as cx and cy and the radius of the centroid circle ?

And how do I find if a point is within the triangle or not ?

enter image description here

PS: I am building this for android , but this question is language agnostic.

Answer

Xantix picture Xantix · Jul 14, 2012

For your first question

Point C in your diagram above is simple, just ( cx, cy + r ).

I can think of two fairly easy ways to get the points a and b:

First Method: Pretend that (cx,cy) is the origin and rotate point C by 60 degrees and by 120 degrees in order get a and b. This can be accomplished with the formula:

  • b.x = c.x * cos( 120 degrees ) - ( c.y * sin( 120 degrees ) )
  • b.y = c.x * sin( 120 degrees ) + ( c.y * cos( 120 degrees ) )
  • a.x = c.x * cos( 240 degrees ) - ( c.y * sin( 240 degrees ) )
  • a.y = c.x * sin( 240 degrees ) + ( c.y * cos( 240 degrees ) )

Also take a look at this article on wikipedia.

Second Method: draw a line which passes through (c.x, c.y) and has a -30 degree slope. Where that line intersects with the circle will be point b. The circle is defined by the equation:

 ( x - c.x )^2 + ( y - c.y )^2 = r^2 

(note, there will be two intersection points, so choose the right one).

Then do the same with a positive 30 degree angle line through (c.x, c.y) to get point a.

Your lines would have slopes: 1 / sqrt(3) and -1 / sqrt(3)

For your second question

Once you have the points A, B, and C that form the equilateral triangle, one of the fastest and easiest ways to detect if a point (x,y) lies in the triangle is based on the cross product and vectors.

Basically, see if (x,y) is to the left of the "vector" A->B. Then see if it is to the left of B->C. Then check to see if it is to the left of C->A.

The following method quoted from here lets you check if a point is to the left of a vector.

public bool isLeft(Point A, Point B, Point C){
    return ((B.x - A.x)*(C.y - A.y) - (B.y - A.y)*( C.x - A.x)) > 0;
}

In the method A = line point1, b = line point2, and c = point to check against.