How to Detect Rectangle Collision in Java
The Java programming language is an object-oriented language developed by Sun and since acquired by Oracle. Object-oriented languages focus on objects, which define a state and behavior for some abstract entity. For example, a “Rectangle” object has a state that consists of its height, width, x-position and y-position. It also has behavior and can be resized, moved and tested to see if it intersects another rectangle. An easy way to test for collisions is to use the “intersects” method on two “Rectangle” objects.
Things You'll Need
- Java Software Development Kit with NetBeans Integrated Development Environment (IDE) Bundle
Instructions
-
-
1
Load the NetBeans integrated development environment (IDE) by clicking on its program icon. When the program loads, navigate to “New/New Project” and select “Java Application” from the list on the right side of the screen. A new source code file appears in the NetBeans text editor. The source code file contains an empty main method.
-
2
Create two “Rectangle” objects. Each rectangle can be initialized with a height, width, x-location and y-location. Write the following two statements inside the curly brackets of the main method to create these two objects:
Rectangle rectOne = new Rectangle(10, 10, 0, 0);
Rectangle rectTwo = new Rectangle(10, 10, 5, 5); -
-
3
Test to see if “rectOne” intersects “rectTwo.” The “intersects” method returns either true or false, depending on the position of the rectangles. If you look back at the previous step, you will see that both rectangles have the same size: 10 by 10. The position of “rectOne” is (0,0), while the position of “rectTwo” is (5,5). This means that “rectTwo” overlaps “rectOne” with a quarter of its area. Therefore, the “intersects” method returns true in the following statement:
bool x = rectOne.intersects(rectTwo);
-
4
Print out the result of the “intersects” method like this:
System.Out.Println(x);
-
5
Run the program by pressing the “Play” button, located in the main toolbar. The program prints out the word “True,” since both rectangles intersect.
-
1