You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.1 KiB

  1. package collider;
  2. import java.awt.Color;
  3. import gameobjects.*;
  4. import org.apache.logging.log4j.Logger;
  5. import org.apache.logging.log4j.LogManager;
  6. /** Collider for round objects */
  7. public class CircleCollider extends Collider {
  8. double x;
  9. double y;
  10. double vx;
  11. double vy;
  12. double r;
  13. private static Logger logger = LogManager.getLogger(Collider.class);
  14. /**
  15. * Constructor which sets the radius to be respected for collisions.
  16. *
  17. * @param id String unique name for the collider instance
  18. * @param o GameObject it belongs to
  19. * @param radius radius in pixels to use as a size
  20. */
  21. public CircleCollider(String id, GameObject o, double radius) {
  22. super(id, o);
  23. this.r = radius;
  24. }
  25. /** simple concatenation of all attributes (x,y,r) */
  26. public String toString() {
  27. return "circ:" + x + " " + y + "/" + r + " ";
  28. }
  29. /**
  30. * calculates the collission of this with other collider
  31. *
  32. * @param _c2 the other collider
  33. * @return true if a collision was detected
  34. * @throws Exception in case the math operations are invalid (due to illegal values of x y or
  35. * radius)
  36. */
  37. public boolean checkCollisionCircCirc(Collider _c2) throws Exception {
  38. CircleCollider c2 = (CircleCollider) _c2;
  39. CircleCollider c1 = this;
  40. logger.trace(c1.x + " " + c1.y + " " + c1.r + " " + c2.x + " " + c2.y+ " " + c2.r);
  41. int kathete1 = (int) (Math.abs(c2.gameobject.getX() - c1.gameobject.getX()));
  42. int kathete2 = (int) (Math.abs(c2.gameobject.getX() - c1.gameobject.getY()));
  43. int hypothenuse = (int) (c1.r + c2.r);
  44. logger.trace(kathete1 + " " + kathete2 + " " + hypothenuse + " ");
  45. if (((kathete1 ^ 2) + (kathete2 ^ 2)) <= (hypothenuse ^ 2)) {
  46. logger.trace("Collision");
  47. return true;
  48. }
  49. return false;
  50. }
  51. @Override
  52. public boolean collidesWith(Collider other) {
  53. // circ circ
  54. try {
  55. return checkCollisionCircCirc(other);
  56. } catch (Exception e) {
  57. }
  58. try {
  59. return other.collidesWith(this);
  60. } catch (Exception e) {
  61. }
  62. throw new RuntimeException("Collider type not implemented!");
  63. }
  64. private Color color = Color.WHITE;
  65. }