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.

83 lines
2.1 KiB

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