@tdurtschi/bug
Version:
Bug is a simulation that models a weevil walking around in an HTML canvas.
84 lines • 3.23 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isPointInsideEntity = void 0;
var bug_1 = __importDefault(require("./entities/bug/bug"));
var Victor = require("victor");
var EntityUpdater = (function () {
function EntityUpdater(entityManager) {
this.entityManager = entityManager;
this.frame = 0;
this.getCollisions = function (entity, otherEntities) {
var collisions = [];
otherEntities.forEach(function (otherEntity) {
if (isIntersecting(entity, otherEntity) &&
!twoBugsHaveDifferentDirection(entity, otherEntity)) {
collisions.push(otherEntity);
}
});
return collisions;
};
}
EntityUpdater.prototype.update = function () {
this.updateAllEntities();
this.frame = this.frame + 1;
};
EntityUpdater.prototype.updateAllEntities = function () {
var _this = this;
var entities = this.entityManager.getEntities();
entities.forEach(function (entity) {
if (entity.updateSpeed !== 0 && _this.frame % entity.updateSpeed == 0) {
entity.update(_this.getCollisions(entity, entities));
}
});
};
return EntityUpdater;
}());
exports.default = EntityUpdater;
var areTwoEntitiesIntersecting = function (e1, e2) {
var _a = e1.pos, x1 = _a.x, y1 = _a.y, _b = e1.size, width1 = _b.x, height1 = _b.y;
var _c = e2.pos, x2 = _c.x, y2 = _c.y, _d = e2.size, width2 = _d.x, height2 = _d.y;
return (x2 < x1 + width1 &&
x2 + width2 > x1 &&
y2 < y1 + height1 &&
height2 + y2 > y1);
};
var isIntersecting = function (obj1, obj2) {
var _a = fixBugPosition(obj1), pos1 = _a[0], size1 = _a[1];
var _b = fixBugPosition(obj2), pos2 = _b[0], size2 = _b[1];
if (obj2 !== obj1 &&
areTwoEntitiesIntersecting({ pos: pos1, size: size1 }, { pos: pos2, size: size2 })) {
return true;
}
return false;
};
exports.isPointInsideEntity = function (entity, x, y) {
var newPos;
if (entity instanceof bug_1.default && entity.direction.x > 0) {
newPos = entity.pos.clone().subtractScalarX(entity.size.x);
}
return areTwoEntitiesIntersecting(newPos ? { pos: newPos, size: entity.size } : entity, {
pos: new Victor(x - 1, y),
size: new Victor(3, 1),
});
};
function fixBugPosition(obj) {
var newPos = obj.pos;
var newSize = obj.size;
if (obj instanceof bug_1.default && obj.direction.x > 0) {
newPos = obj.pos.clone().subtractScalarX(1);
}
if (obj instanceof bug_1.default) {
}
return [newPos, newSize];
}
function twoBugsHaveDifferentDirection(entity, otherEntity) {
if (!(entity instanceof bug_1.default) || !(otherEntity instanceof bug_1.default))
return false;
var distBetween = Math.abs(entity.pos.x - otherEntity.pos.x);
return (entity.direction.x != otherEntity.direction.x &&
distBetween > entity.size.x * 0.5);
}
//# sourceMappingURL=entity-updater.js.map