9

Я написал нечто вроде сетки, но скрипт работает только наполовину. Если нажать куда-либо, а затем отпустить, сетка совершит попытку восстановиться, как и до нажатия, но попытка окажется неудачной и все квадраты продолжат дрожать.

Мой вопрос: как прекратить дрожание? Я совершенно без понятия, как это сделать.

<!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>

1
  • Там где-то надо прописать дельту. Если координата примерно в этой дельте, то стопорить.Именно стопорить, а не делать wall.x += и wall.y +=. 2 июл 2019 в 20:47

1 ответ 1

10

Как Вам такой вариант?

Мне кажется в Вашем случае не стоит увеличивать скорость при отлете от точки назначения, когда квадраты возвращаются

введите сюда описание изображения

let ctx = can.getContext('2d'),
  rnd = (min, max) => Math.floor(Math.random() * ((max + 1) - min) + min),
  walls = [],
  mouse = {x: 0, y: 0, down: false },
  Wall = function(x, y, width, height, color, speed) {
      this.x = x,
      this.y = y,
      this.width = width,
      this.height = height,
      this.color = color,
      this.speed = speed,
      this.nativePosition = {x,y},
      this.velocity = {x: 0, y: 0, friction: .91}
  },
  size = {width: 26,height: 26};

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, "#999", rnd(2, 4)))
  }
};

(onresize = e => {
  can.width = innerWidth;
  can.height = innerHeight;
})();

document.onmousemove = e => {
  mouse.x = e.clientX;
  mouse.y = e.clientY;
};

document.onmousedown = e => mouse.down = true;
document.onmouseup = e => mouse.down = false;

(loop = () => {
  ctx.fillStyle = "#0008";
  ctx.fillRect(-3e38, -3e38, 3e38 * 2, 3e38 * 2);

  walls.forEach(wall => {
    let a, b, d = mouse.down;
    if (d) {
      a = mouse.x - wall.x - wall.width / 2;
      b = mouse.y - wall.y - wall.height / 2;
      len = Math.sqrt(a * a + b * b) || 1;
      a = a / len * wall.speed;
      b = b / len * wall.speed;
    } else {
      a = wall.nativePosition.x - wall.x;
      b = wall.nativePosition.y - wall.y;
    }

    wall.velocity.x *= wall.velocity.friction;
    wall.velocity.y *= wall.velocity.friction;
    wall.velocity.x += a * Math.random() / (d ? 1 : 5);
    wall.velocity.y += b * Math.random() / (d ? 1 : 5);
    wall.x += wall.velocity.x;
    wall.y += wall.velocity.y

    ctx.strokeStyle = wall.color;
    ctx.strokeRect(wall.x+3, wall.y+3, wall.width-3, wall.height-3)
  });

  requestAnimationFrame(loop)
})();
body, #can {
  margin: 0;
  background-color: black;
  overflow: hidden;
}
<canvas id="can"></canvas>

1
  • Просто Супер...
    – doox911
    3 июл 2019 в 19:32

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.