package Collision import Entity public constant globalWorld = new CollisionWorld(playableMapRect) public tuple rectangle(vec2 min, vec2 max) public function rectangle.intersect(rectangle other) returns boolean return not (other.min.x > this.max.x or other.max.x < this.min.x or other.max.y > this.min.y or other.min.y < this.max.y) public function rectangle.contains(vec2 point) returns boolean return point.x > this.min.x and point.x < this.max.x and point.y > this.min.y and point.y < this.max.y public interface CollisionShape abstract function intersect(Entity e1, Entity e2) returns boolean public abstract class CollisionListener abstract function onHit(Entity other) public class SphereShape implements CollisionShape override function intersect(Entity e1, Entity e2) returns boolean return (e1.getPos() + vec3(0, 0, e1.radius / 2) ).distanceToSq(e2.getPos() + vec3(0, 0, e1.radius / 2)) <= e1.radius2 + e2.radius2 public constant SHAPE_SPHERE = new SphereShape() public function registerCollider(Entity e, CollisionShape shape, CollisionListener listener) shapes[e castTo int] = shape listeners[e castTo int] = listener globalWorld.colliders.add(e) public function registerCollidable(Entity e, CollisionListener listener) listeners[e castTo int] = listener globalWorld.collidables.add(e) public function removeCollidable(Entity e) if listeners[e castTo int] != null destroy listeners[e castTo int] listeners[e castTo int] = null globalWorld.collidables.remove(e) public function removeCollider(Entity e) if listeners[e castTo int] != null destroy listeners[e castTo int] listeners[e castTo int] = null globalWorld.colliders.remove(e) CollisionShape array shapes CollisionListener array listeners public class CollisionWorld rectangle worldBounds let colliders = new LinkedList() let collidables = new LinkedList() construct(rect re) worldBounds = rectangle(vec2(re.getMinX(), re.getMinY()), vec2(re.getMaxX(), re.getMaxY())) function update(real _delta) for collider in colliders for collidable in collidables if collider != null and not collider.done and collidable != null and not collidable.done and collider != collidable and shapes[collider castTo int].intersect(collider, collidable) listeners[collider castTo int].onHit(collidable) listeners[collidable castTo int].onHit(collider)