0

I'm writing a shape drawing function and want to check if the user clicks inside of a triangle shape like a hit test.

This is what I have so far:

public void draw(Graphics g) 
{
    int x[] = { (x1 + x2) / 2, x1, x2}; 
    int y[] = { y1, y2, y2}; 
    int numberOfPoints = 3;
    g.setColor(color);
    g.fillPolygon(x, y, numberOfPoints);
}

public boolean hitTest(int x, int y) 
{
    return x > ((x1 + x2) / 2) && x < x2 && y > y1 && y < y2;
}

This partially works for the triangle, but the right side of it still isn't hit-testing correctly. Any idea as to why this hitTest function wouldn't work?

Joshua
  • 41
  • 4
  • Pick your [answer](https://stackoverflow.com/questions/2049582/how-to-determine-if-a-point-is-in-a-2d-triangle) from that PAQ? – Idle_Mind Dec 08 '19 at 17:13

2 Answers2

0

Do not directly draw the polygon, instead create a Polygon. Then you can draw that shape. You might want to have al look at About drawing a Polygon in java

hotzst
  • 7,238
  • 9
  • 41
  • 64
0

To begin with, you need 3-points to have a triangle before inspecting if it is inside like (x1, y1), (x2, y2) and (x3, y3). Then, you need to calculate its area prior to vet the containment.

Since there are a plethora of topics about it you can scrutinize to grasp the formulae's logic. One of the is the following from @Idle_Mind comment.

s = 1/(2*Area)*(p0y*p2x - p0x*p2y + (p2y - p0y)*px + (p0x - p2x)*py);
t = 1/(2*Area)*(p0x*p1y - p0y*p1x + (p0y - p1y)*px + (p1x - p0x)*py);

where Area is the (signed) area of the triangle:

Area = 0.5 *(-p1y*p2x + p0y*(-p1x + p2x) + p0x*(p1y - p2y) + p1x*p2y);

It can be tested by clicking inside or outside of the shown triangle via this link which makes random triangles at each running.