2

Я написал код, создающий круги по удержанию мыши, притом эти круги имеют рандомную скорость и при столкновении с границей экрана она инвертируется. Проблема в том, что если круги спавнятся на границе экрана, они могут передвигаться только "по" этой границе и за её пределы выйти не могут. Скорость постоянно инвертируется и из-за этого они как бы стоят на месте по одной (или двум, если заспавнятся в углу) координатам, что с этим делать я не знаю. Даже как назвать этот баг я не знаю.

Если не поняли, то просто удерживайте мышь при x = 0 координате.

<!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.random() * ((max + 1) - min) + min,
		mouse = {
			x: 0,
			y: 0,
			down: false
		},
		circles = [],
		Circle = class {
			constructor(position, radius, color, speed) {
				this.position = position,
				this.radius = radius,
				this.color = color,
				this.speed = speed
			}
		}, createCircle = (x, y, radius, color, speed) => circles.push( new Circle({x: x, y: y}, radius, color, speed) ),
		player = {
			position: {
				x: 0,
				y: 0
			},
			radius: 20,
			color: "#0FF"
		};

		onresize = e => {
			can.width = innerWidth;
			can.height = innerHeight
		};
		can.style.background = "#000";
		onresize();

		document.onmousedown = e => mouse.down = true;
		document.onmouseup = () => mouse.down = false;
		document.onmousemove = e => {
			mouse.x = e.clientX;
			mouse.y = e.clientY
		};

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

			if(mouse.down) {
				createCircle(mouse.x, mouse.y, 20, "#FFF", {x: rnd(-10, 10), y: rnd(-10, 10)});
			};

			circles.forEach(circle => {
				let a = player.position.x - circle.position.x,
				b = player.position.y - circle.position.y,
				len = Math.sqrt(a * a + b * b);

				// Вот тут проблемы :|
				if(circle.position.x < circle.radius - circle.speed.x || circle.position.x > innerWidth - circle.radius - circle.speed.x) circle.speed.x = -circle.speed.x;
				if(circle.position.y < circle.radius - circle.speed.y || circle.position.y > innerHeight - circle.radius - circle.speed.y) circle.speed.y = -circle.speed.y;

				circle.position.x += circle.speed.x;
				circle.position.y += circle.speed.y;

				// Если расстояние (len) меньше суммы радиусов игрока и конкретного круга (если игрок коснулся круга), то цвет круга нужно изменить.
				circle.color = len < circle.radius + player.radius ? "#F00" : "#FFF";
				ctx.strokeStyle = circle.color;
				ctx.beginPath();
				ctx.arc(circle.position.x, circle.position.y, circle.radius, 0, Math.PI * 2);
				ctx.stroke()
			});

			player.position.x = mouse.x;
			player.position.y = mouse.y;

			ctx.strokeStyle = player.color;
			ctx.beginPath();
			ctx.arc(player.position.x, player.position.y, player.radius, 0, Math.PI * 2);
			ctx.stroke();

			requestAnimationFrame(loop)
		})();
	</script>
</body>
</html>

1
  • А зачем Вы удалили свой вопрос про круги? Я бы завтра возможно накидал пример ответа =) 5 июл 2019 в 22:08

1 ответ 1

0

Определяйте знак скорости абсолютно, а не инвертируйте его

Тут логика такая: берем знак положения шарика, если он отрицательный - значит нам нужно положительное направление. Все.

circle.speed.x = -Math.abs(circle.speed.x) * Math.sign(circle.position.x - circle.radius);
circle.speed.y = -Math.abs(circle.speed.y) * Math.sign(circle.position.y - circle.radius);

<!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.random() * ((max + 1) - min) + min,
		mouse = {
			x: 0,
			y: 0,
			down: false
		},
		circles = [],
		Circle = class {
			constructor(position, radius, color, speed) {
				this.position = position,
				this.radius = radius,
				this.color = color,
				this.speed = speed
			}
		}, createCircle = (x, y, radius, color, speed) => circles.push( new Circle({x: x, y: y}, radius, color, speed) ),
		player = {
			position: {
				x: 0,
				y: 0
			},
			radius: 20,
			color: "#0FF"
		};

		onresize = e => {
			can.width = innerWidth;
			can.height = innerHeight
		};
		can.style.background = "#000";
		onresize();

		document.onmousedown = e => mouse.down = true;
		document.onmouseup = () => mouse.down = false;
		document.onmousemove = e => {
			mouse.x = e.clientX;
			mouse.y = e.clientY
		};

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

			if(mouse.down) {
				createCircle(mouse.x, mouse.y, 20, "#FFF", {x: rnd(-10, 10), y: rnd(-10, 10)});
			};

			circles.forEach(circle => {
				let a = player.position.x - circle.position.x,
				b = player.position.y - circle.position.y,
				len = Math.sqrt(a * a + b * b);

				// Вот тут проблемы :|
				if (circle.position.x < circle.radius - circle.speed.x || 
           circle.position.x > innerWidth - circle.radius - circle.speed.x) 
              circle.speed.x = -Math.abs(circle.speed.x) * Math.sign(circle.position.x - circle.radius);
				if (circle.position.y < circle.radius - circle.speed.y || 
           circle.position.y > innerHeight - circle.radius - circle.speed.y) 
              circle.speed.y = -Math.abs(circle.speed.y) * Math.sign(circle.position.y - circle.radius);

				circle.position.x += circle.speed.x;
				circle.position.y += circle.speed.y;

				// Если расстояние (len) меньше суммы радиусов игрока и конкретного круга (если игрок коснулся круга), то цвет круга нужно изменить.
				circle.color = len < circle.radius + player.radius ? "#F00" : "#FFF";
				ctx.strokeStyle = circle.color;
				ctx.beginPath();
				ctx.arc(circle.position.x, circle.position.y, circle.radius, 0, Math.PI * 2);
				ctx.stroke()
			});

			player.position.x = mouse.x;
			player.position.y = mouse.y;

			ctx.strokeStyle = player.color;
			ctx.beginPath();
			ctx.arc(player.position.x, player.position.y, player.radius, 0, Math.PI * 2);
			ctx.stroke();

			requestAnimationFrame(loop)
		})();
	</script>
</body>
</html>

PS: похожий ответ

Ваш ответ

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

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