'Click inside a figure
How can I know if the user has clicked inside a Pentagon and a Ellipse? I was able to create a method for Circle, Triangle and Rect, but I got stucked in those two figures.
Rect:
public boolean clicked(int x, int y) {
return (this.getX() <= x && x <= this.getX() + this.getW() && this.getY() <= y && y <= this.getY() + this.getH());
}
Circle:
public boolean clicked(int x, int y) {
int cx = this.getX() + (this.getW() / 2);
int cy = this.getY() + (this.getH() / 2);
int r = this.getW() / 2;
return Math.sqrt(Math.pow(x - cx, 2) + Math.pow(y - cy, 2)) <= r;
}
Triangle:
private int[] xdir = { this.getX(), ((this.getW()) / 2) + this.getX(), this.getW() + this.getX() };
private int[] ydir = { this.getY() + this.getH(), this.getY(), this.getY() + this.getH() };
public boolean clicked(int x, int y) {
double A = area(this.xdir[0], this.ydir[0],this.xdir[1], this.ydir[1], this.xdir[2], this.ydir[2]);
double A1 = area(x, y, this.xdir[1], this.ydir[1], this.xdir[2], this.ydir[2]);
double A2 = area(this.xdir[0], this.ydir[0], x, y, this.xdir[2], this.ydir[2]);
double A3 = area(this.xdir[0], this.ydir[0], this.xdir[1], this.ydir[1], x, y);
return A == A1 + A2 + A3;
}
public double area(int x1, int y1, int x2, int y2, int x3, int y3) {
return Math.abs((x1*(y2-y3) + x2*(y3-y1)+ x3*(y1-y2))/2.0);
}
Just to let you aware, my Pentagon and Ellipse were created this was:
Ellipse:
g2d.setColor(this.outline);
g2d.draw(new Ellipse2D.Double(this.getX(), this.getY(), this.getW() / 2, this.getH()));
g2d.setColor(this.background);
g2d.fillOval(this.getX(), this.getY(), this.getW() / 2, this.getH());
Pentagon:
int[] xdir = { (int) (this.getX() + this.getW() / 2), this.getX() + this.getW(),
(int) (this.getX() + this.getW() * 0.75), (int) (this.getX() +
this.getW() * 0.25), this.getX() };
int[] ydir = { this.getY(), (int) (this.getY() + this.getH() * 0.40), this.getY() + this.getH(), this.getY() + this.getH(), (int) (this.getY() + this.getH() * 0.40) };
g2d.setColor(this.outline);
g2d.drawPolygon(xdir, ydir, 5);
g2d.setColor(this.background);
g2d.fillPolygon(xdir, ydir, 5);
As you can see, I always return true or false, so I need to do the same with both figures left. Besides that, I read something about collision but I didn't understood how to implement it without having issues with the others figures.
This is how my project looks like: Project image
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
