Skip to content

Instantly share code, notes, and snippets.

@luketn
Created March 24, 2019 01:38
Show Gist options
  • Save luketn/5e64f71c84a29eca159d7882bbfaf17c to your computer and use it in GitHub Desktop.
Save luketn/5e64f71c84a29eca159d7882bbfaf17c to your computer and use it in GitHub Desktop.
Little demo of detecting collisions with shapes
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Ellipse2D;
public class MainFrame extends JFrame implements MouseListener {
private int x;
private int y;
public static void main(String[] args) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
MainFrame mainFrame = new MainFrame();
mainFrame.x = screenSize.width/2 - 50;
mainFrame.y = screenSize.height/2 - 50;
mainFrame.setSize(screenSize.width, screenSize.height);
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainFrame.addMouseListener(mainFrame);
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.BLACK);
g2.fillRect(0,0, this.getWidth(), this.getHeight());
Shape circle = new Ellipse2D.Double(x,y,100,100);
Shape house = drawHouse(500, 500, 50);
if (circle.intersects(house.getBounds())) {
g2.setColor(Color.RED);
g2.fill(circle);
}
g2.setColor(Color.WHITE);
g2.draw(circle);
g2.setColor(Color.RED);
g2.draw(house);
}
private Shape drawHouse(int x, int y, int wallLength) {
int bottomLeftX = x - wallLength /2;
int bottomLeftY = y + wallLength /2;
Polygon house = new Polygon();
house.addPoint(bottomLeftX, bottomLeftY);
house.addPoint(bottomLeftX + 50, bottomLeftY);
house.addPoint(bottomLeftX + wallLength, bottomLeftY - wallLength);
house.addPoint(bottomLeftX + wallLength /2, bottomLeftY - wallLength - wallLength /2);
house.addPoint(bottomLeftX, bottomLeftY - wallLength);
house.addPoint(bottomLeftX, bottomLeftY);
return house;
}
@Override
public void mouseClicked(MouseEvent e) {
this.x = e.getX() - 50;
this.y = e.getY() - 50;
this.repaint();
}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment