NasaMarsApp / sketch.js
sd4m's picture
Create sketch.js
7209c14 verified
// /src/sim/sketch.js
import { runStore } from '../state/runStore.js';
let canvas;
let bot = { x: 0, y: 0 };
let targetIdx = 0;
let isRunning = false;
let startTime;
export function createSim(containerEl) {
const w = containerEl.clientWidth;
const h = containerEl.clientHeight;
canvas = new p5(p => {
p.setup = () => {
p.createCanvas(w, h);
p.frameRate(60);
};
p.draw = () => {
p.background(0);
p.fill(0, 20, 60);
p.noStroke();
// dibuja puntos
runStore.points.forEach((pt, idx) => {
if (!pt.collected) {
p.fill(0, 0, 255);
p.circle(pt.x * w, pt.y * h, 5);
}
});
if (isRunning && targetIdx < runStore.order.length) {
const tgt = runStore.points[runStore.order[targetIdx]];
const tx = tgt.x * w, ty = tgt.y * h;
// mover bot hacia target con lerp
const lerpFactor = 0.02 * runStore.params.speed;
bot.x = p.lerp(bot.x, tx, lerpFactor);
bot.y = p.lerp(bot.y, ty, lerpFactor);
p.fill(255, 165, 0);
p.noStroke();
p.circle(bot.x, bot.y, 8);
const d = p.dist(bot.x, bot.y, tx, ty);
if (d < 2) {
// alcanzado
runStore.markCollected(runStore.order[targetIdx]);
runStore.recordStep({ x: bot.x / w, y: bot.y / h }, { x: tgt.x, y: tgt.y });
targetIdx += 1;
}
} else {
// dibujar bot si no en running (posición inicial)
p.fill(255, 165, 0);
p.circle(bot.x, bot.y, 8);
}
};
}, containerEl);
}
// funciones para controlar el sim
export function resetSim() {
runStore.resetRun();
isRunning = false;
targetIdx = 0;
}
export function startSim(params) {
runStore.startRun(params);
isRunning = true;
targetIdx = 0;
bot.x = 0;
bot.y = 0;
startTime = performance.now();
}
export function stopSim() {
isRunning = false;
const elapsed = (performance.now() - startTime) / 1000;
runStore.finalize(elapsed, /* energy factor kms->kWh */ 1.0);
}