-
Notifications
You must be signed in to change notification settings - Fork 0
Hitbox class
To create a hitbox, you need to initialise it like shown in the following example.
The constructor takes the following parameters:
Point... points:
A set of points, which represent an n-shape. If only two points are given, it'll create another two points to form a rectangle. If only one point or no point is given, it'll throw an error.
//Creates a hitbox that looks like a rectangle
Hitbox hitbox = new Hitbox(new Point(100, 100), Point(200, 200));
//Creates a hitbox that looks like an triangle
Hitbox hitbox = new Hitbox(new Point(100, 100), new Point(100, 200), Point(200, 200));
The main use case of a hitbox is collision detection, or checking if a point is inside a given shape.
This can be achieved via the following method:
This method returns true
if a hitbox or a point is inside the hitbox that executed the method.
Point test:
The point you want to test. (e. g. new Point(100, 100)
)
Hitbox test:
The hitbox you want to test.
//Create a hitbox
Hitbox hitbox = new Hitbox(new Point(100, 100), Point(200, 200));
//Check if a point is inside the hitbox
if(hitbox.isInside(new Point(150, 150))){
System.out.println("The point is inside!");
}
//Create two hitboxes
Hitbox a = new Hitbox(new Point(100, 100), Point(200, 200));
Hitbox b = new Hitbox(new Point(50, 50), Point(150, 150));
//Check if hitbox b is inside the hitbox a
if(hitbox.isInside(b)){
System.out.println("The hitbox b is inside!");
}
Because rotating hitboxes is not as easy, as rotating a picture, this class includes a rotate
method.
double angle:
The angle by which the Hitbox should be turned in radians.
int centerX:
The x Point, you want the hitbox rotated around.
int centerY:
The y Point, you want the hitbox rotated around.
If x and y point are not given, the method will calculate the middle of the hitbox and use that as an rotation point.
//Create an hitbox
Hitbox a = new Hitbox(new Point(100, 100), Point(200, 200));
//Rotate the hitbox a by 0.1 Rad around its center
a.rotate(0.1);
//Rotatae the hitbox a by 30 Deg around its center
a.rotate(Math.toRadians(30));
//Rotate the hitbox a by 0.1 Rad around x: 50, y: 50
a.rotatae(0.1, 50, 50);
Sometimes you want a hitbox to be rendered in your program for debug purposes or just for design.
You can do that via the following way:
//Create an hitbox
Hitbox a = new Hitbox(new Point(100, 100), Point(200, 200));
//Show the hitbox in the render loop.
@Override
public void renderLoop() {
//note if you cant see the object try using a different color to render it.
Graphics.g.draw(a.getShape());
}
Returns the shape
of an hitbox.