SpeedexUltimate SpeedexUltimate - 1 year ago 74
Java Question

How do you create 2 Rectangle objects that will collide and be detected in Java?

Also, is it possible to collide 2 Oval objects?

public void paint(Graphics g){
g.fillRect(k, l, 100, 100);<br/>
g.fillRect(n, m, 100, 100);<br/>
for(int i=0; i<2; i++){<br/>

Answer Source

It appears that you are using Swing for your graphics. Although actually providing code for your question would be a rather complex task, I will try to guide you in the correct direction.

It might be best to encapsulate the rectangles (or ovals) into their own classes. Give the objects a method like drawSelf(Graphics g) and pass in the Graphics object. Also, give the classes fields to keep track of their current positions and sizes.

Then, for collisions, you might try making a class along the lines of a CollisionDetector. All of your shape objects would have-a CollisionDetector, and everytime a shape moves you ask all shapes to check with their CollisionDetectors, which in turn check all other Detectors to see if they overlap.