Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Collision {
- static CanvasElement canvas = new CanvasElement();
- static void init() {
- query('body').append(canvas);
- }
- static bool collides(BoundingBox a, BoundingBox b) {
- List<Vector2> A = a.getPoints();
- List<Vector2> B = b.getPoints();
- Vector2 Axis1 = new Vector2(A[1].x-A[0].x,A[1].y-A[0].y);
- Vector2 Axis2 = new Vector2(A[1].x-A[2].x,A[1].y-A[2].y);
- Vector2 Axis3 = new Vector2(B[0].x-B[3].x,B[0].y-B[3].y);
- Vector2 Axis4 = new Vector2(B[0].x-B[1].x,B[0].y-B[1].y);
- return _projectionOverlap(Axis1,A,B) &&
- _projectionOverlap(Axis2,A,B) &&
- _projectionOverlap(Axis3,A,B) &&
- _projectionOverlap(Axis4,A,B);
- }
- static bool _projectionOverlap (Vector2 v,List<Vector2> A, List<Vector2> B) {
- List aVal = _projectPoints(v,A);
- double aMin = aVal[0];
- double aMax = aVal[1];
- List bVal = _projectPoints(v,B);
- double bMin = bVal[0];
- double bMax = bVal[1];
- if (aMin <= bMin&& bMin <= aMax)
- return true;
- if (aMin <= bMax&& bMax <= aMax)
- return true;
- return false;
- }
- static List _projectPoints(Vector2 v, List<Vector2> A) {
- double aMin;
- double aMax;
- A.forEach((Vector2 p) {
- num proj = (p.x*v.x+p.y*v.y)/(Math.pow(p.x,2)+Math.pow(p.y,2));
- num x = proj*v.x;
- num y = proj*v.y;
- num val = (x*v.x)+(y*v.y);
- if (aMin == null) {
- aMin = val;
- aMax = val;
- } else {
- aMin = Math.min(val, aMin);
- aMax = Math.max(val, aMax);
- }
- });
- return [aMin,aMax];
- }
- }
- class BoundingBox {
- CollidableEntity parent;
- int offsetX;
- int offsetY;
- int width;
- int height;
- double rotation;
- BoundingBox (this.parent,this.offsetX,this.offsetY,this.width,this.height,[this.rotation=0.0]);
- List<Vector2> getPoints() {
- Matrix2 translation = new Matrix2.rotation(rotation);
- int x = offsetX+parent.x;
- int y = offsetY+parent.y;
- Vector2 move = new Vector2(x.toDouble(),y.toDouble());
- Vector2 topLeft = translation.transform(new Vector2(-(width/2),-(height/2)))+move;
- Vector2 topRight = translation.transform(new Vector2((width/2),-(height/2)))+move;
- Vector2 bottomLeft = translation.transform(new Vector2(-(width/2),(height/2)))+move;
- Vector2 bottomRight = translation.transform(new Vector2((width/2),(height/2)))+move;
- return [topLeft,topRight,bottomRight,bottomLeft];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement