refactor: better magnetism

This commit is contained in:
cha0s 2024-07-04 12:58:33 -05:00
parent fcefe1a620
commit f1d1422e7a

View File

@ -1,5 +1,5 @@
import {System} from '@/ecs/index.js';
import {normalizeVector} from '@/util/math.js';
import {distance, normalizeVector} from '@/util/math.js';
export default class Attract extends System {
@ -9,7 +9,7 @@ export default class Attract extends System {
};
}
tick() {
tick(elapsed) {
for (const entity of this.select('default')) {
const {Magnet, Position} = entity;
const aabb = {
@ -18,6 +18,8 @@ export default class Attract extends System {
y0: Position.y - Magnet.strength / 2,
y1: Position.y + (Magnet.strength / 2) - 1,
};
let s = Magnet.strength;
s = s * s;
for (const other of this.ecs.system('Colliders').within(aabb)) {
if (other === entity || !other.Magnetic) {
continue;
@ -27,10 +29,21 @@ export default class Attract extends System {
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,
});
let d = distance(entity.Position, other.Position);
if (d > 0) {
const inv = s * (1 / (d * d));
let impulse = {
x: toward.x * inv,
y: toward.y * inv,
};
if (Math.sign(entity.Position.x - (impulse.x * elapsed + other.Position.x)) !== Math.sign(difference.x)) {
impulse.x = difference.x / elapsed;
}
if (Math.sign(entity.Position.y - (impulse.y * elapsed + other.Position.y)) !== Math.sign(difference.y)) {
impulse.y = difference.y / elapsed;
}
other.Forces.applyImpulse(impulse);
}
}
}
}