import {System} from '@/ecs/index.js'; import {normalizeVector} from '@/util/math.js'; export default class Attract extends System { static queries() { return { default: ['Magnet'], }; } tick() { for (const entity of this.select('default')) { const {Magnet, Position} = entity; const aabb = { x0: Position.x - Magnet.strength / 2, x1: Position.x + (Magnet.strength / 2) - 1, y0: Position.y - Magnet.strength / 2, y1: Position.y + (Magnet.strength / 2) - 1, }; for (const other of this.ecs.system('Colliders').within(aabb)) { if (other === entity || !other.Magnetic) { continue; } const difference = { x: entity.Position.x - other.Position.x, y: entity.Position.y - other.Position.y, }; const toward = normalizeVector(difference); other.Forces.applyImpulse({ x: Math.abs(toward.x) * 8 * Magnet.strength / difference.x, y: Math.abs(toward.y) * 8 * Magnet.strength / difference.y, }); } } } }