Dimitri
Dimitri

Reputation: 1966

Collision detection Graphics 2D

I'm building a simulator that is based on car collisions on the road. The "cars" are basic rectangles drawn using fillRect and setting random x and y coordinates for each car. The kinematics portion of the simulator work perfect except when cars collide. What I'm trying to do is figure out a way to detect collision without re-inventing the wheel. In essence, is there such implementation in Java that helps with this type of situation?

If not, I have an idea that consists of putting every single x and y point in the area of the square into an array for each car. Then if the other car's "area" overlaps a coordinate with the other, then a collision would occur. Could this be a solution, or is there a simpler way of doing this? Perhaps some advice would be great!

Upvotes: 0

Views: 289

Answers (1)

sandymatt
sandymatt

Reputation: 5612

If not, I have an idea that consists of putting every single x and y point in the area of the square into an array for each car.

No need to reinvent the wheel. Are you using Rectangle objects for your cars underneath? You can call methods such as contains and intersects which are part of the Rectangle api to achieve what you want. You need to make sure you check the next movement of the Rectangles, looking for collisions, before you move them.

Look here.

Upvotes: 1

Related Questions