SpeedexUltimate SpeedexUltimate - 5 months ago 29
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.setColor(Color.green);<br/>
g.fillRect(k, l, 100, 100);<br/>
g.setColor(Color.blue);<br/>
g.fillRect(n, m, 100, 100);<br/>
g.setColor(Color.red);<br/>
for(int i=0; i<2; i++){<br/>
g.fillOval((int)x[i],(int)y[i],diameter,diameter);<br/>
}<br/>
}

Answer

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.