itsericwoodward-site-v2/src/assets/_root/webtoys/bbe/scripts/lightning.js

46 lines
1.2 KiB
JavaScript

export const createLightning = (canvas, enemy) => {
const { y: size } = enemy;
var center = { x: canvas.width / 2, y: canvas.height };
var minSegmentHeight = 5;
var roughness = 2;
var maxDifference = size / 5;
let lightning = [];
let segmentHeight = size / 3;
lightning.push({
x: center.x,
y: center.y + 200,
});
lightning.push({
x: Math.random() * (canvas.width - 100) + 50,
y: Math.abs((Math.random() - 0.9) * 100),
});
let currDiff = maxDifference;
while (segmentHeight > minSegmentHeight) {
const newSegments = [];
for (var i = 0; i < lightning.length - 1; i++) {
const start = lightning[i],
end = lightning[i + 1],
midX = (start.x + end.x) / 2,
newX = midX + (Math.random() * 2 - 1) * currDiff;
newSegments.push(start, { x: newX, y: (start.y + end.y) / 2 });
}
newSegments.push(lightning.pop());
lightning = newSegments;
currDiff /= roughness;
segmentHeight /= 2;
}
return lightning;
};
// Get the position of the mouse relative to the canvas
export const getMousePos = (canvasDom, mouseEvent) => {
var rect = canvasDom.getBoundingClientRect();
return {
x: mouseEvent.clientX - rect.left,
y: mouseEvent.clientY - rect.top,
};
};