Я написал нечто вроде сетки, но скрипт работает только наполовину. Если нажать куда-либо, а затем отпустить, сетка совершит попытку восстановиться, как и до нажатия, но попытка окажется неудачной и все квадраты продолжат дрожать.
Мой вопрос: как прекратить дрожание? Я совершенно без понятия, как это сделать.
<!DOCTYPE html>
<html>
<head>
<title>.</title>
<meta charset="UTF-8">
</head>
<body style="margin: 0">
<canvas id="can" style="display: block"></canvas>
<script type="text/javascript">
function getId(o) {return document.getElementById(o)};
let can = getId('can'), ctx = can.getContext('2d'), rnd = (min, max) => Math.floor(Math.random() * ((max + 1) - min) + min),
walls = [], mouse = {
x: 0,
y: 0,
down: false
},
Wall = class {
constructor(x, y, width, height, color, speed, nativePosition) {
this.x = x,
this.y = y,
this.width = width,
this.height = height,
this.color = color,
this.speed = speed,
this.nativePosition = nativePosition,
this.velocity = {
x: 0,
y: 0,
friction: .9
}
}
}, size = {
width: 25,
height: 25
};
for(let x = 0; x < innerWidth / size.width; x++) {
for(let y = 0; y < innerHeight / size.height; y++) {
walls.push( new Wall(x * size.width, y * size.height, size.width, size.height, "#555", rnd(2, 4), {x: x * size.width, y: y * size.height}) )
}
};
onresize = e => {
can.width = innerWidth;
can.height = innerHeight
};
onresize();
can.style.background = "#000";
document.onmousemove = e => {
mouse.x = e.clientX;
mouse.y = e.clientY
};
document.onmousedown = () => mouse.down = true;
document.onmouseup = () => mouse.down = false;
(loop = () => {
ctx.fillStyle = "#0003";
ctx.fillRect(-3e38, -3e38, 3e38 * 2, 3e38 * 2);
walls.forEach(wall => {
if(mouse.down) {
let a = mouse.x - wall.x - wall.width / 2,
b = mouse.y - wall.y - wall.height / 2,
len = Math.sqrt(a * a + b * b), speed = wall.speed;
a = a / (len ? len : 1) * speed;
b = b / (len ? len : 1) * speed;
wall.velocity.x *= wall.velocity.friction;
wall.velocity.y *= wall.velocity.friction;
wall.velocity.x += a;
wall.velocity.y += b;
wall.x += wall.velocity.x;
wall.y += wall.velocity.y
} else {
let a = wall.nativePosition.x - wall.x,
b = wall.nativePosition.y - wall.y,
len = Math.sqrt(a * a + b * b), speed = wall.speed;
a = a / (len ? len : 1) * speed;
b = b / (len ? len : 1) * speed;
wall.velocity.x *= wall.velocity.friction;
wall.velocity.y *= wall.velocity.friction;
wall.velocity.x += a;
wall.velocity.y += b;
wall.x += wall.velocity.x;
wall.y += wall.velocity.y
};
ctx.strokeStyle = wall.color;
ctx.strokeRect(wall.x, wall.y, wall.width, wall.height)
});
requestAnimationFrame(loop)
})();
</script>
</body>
</html>
wall.x +=
иwall.y +=
.