Я пытаюсь сделать простую игру на основе JavaScript, в которой пользователь будет перемещать квадрат по холсту и уклоняться от приближающихся к нему элементов/квадратов (однако это всего лишь план, я далек от этого момента на данный момент).
Проблема, с которой я сталкиваюсь, заключается в том, что всякий раз, когда я делаю значение ширины холста больше высоты, квадрат застревает после достижения нижней части страницы. Вероятно, в моем коде есть ошибка/ошибка, но я ничего не заметил.
Код можно найти здесь или ниже:
// This code was created in CodePen.io, so some parts of it might not make any sense,
// nor are they gonna be useful outside the CodePen platform. Those parts are however only commented.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// character data
var charPositionX = canvas.width / 2;
// Just for the snippet height
var charPositionY = 0;
//var deltaCharPositionX = 10;
//var deltaCharPositionY = 10;
//Removed the init() function, since the elements are loaded.
// start creating elements, first the game environment.
function draw() {
clear();
createRectangleToCoverCanvas();
createChar(charPositionX, charPositionY, 10);
}
function clear() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function createRectangleToCoverCanvas() {
ctx.fillStyle = '#ddd';
ctx.strokeStyle = '#ddd';
ctx.beginPath();
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fill();
ctx.stroke();
}
// now the character
function createChar(x, y, radius) {
ctx.fillStyle = 'white';
ctx.strokeStyle = 'white';
ctx.beginPath();
ctx.rect(x, y, 32, 32);
ctx.fill();
ctx.stroke();
}
var raf,
direction = {
x: 0,
y: 0
};
// set the speed variable for the character
var speed = 5;
function triggerMoveChar(event) {
switch (event.keyCode) {
// left
case 37:
// update the direction object
direction.x = -speed;
// avoid the scrolling
event.preventDefault();
break;
// up
case 38:
direction.y = -speed;
event.preventDefault();
break;
// right
case 39:
direction.x = speed;
event.preventDefault();
break;
//down
case 40:
direction.y = speed;
event.preventDefault();
break;
}
// if the animation haven't been initiated yet, and the direction is not 0, then do it now
if (!raf && (direction.x || direction.y)) moveChar();
}
function releaseMoveChar(event) {
switch (event.keyCode) {
// left
case 37:
//reset this direction
direction.x = 0;
break;
// up
case 38:
direction.y = 0;
break;
// right
case 39:
direction.x = 0;
break;
//down
case 40:
direction.y = 0;
break;
}
if (!direction.x && !direction.y) {
// if none of the directions is set, stop the animation
cancelAnimationFrame(raf);
raf = undefined;
}
}
function moveChar() {
// declare the animation function
var move = function() {
// update the positions without going out of the screen
if (direction.x){
if (
(charPositionX > 0 && charPositionX < canvas.width-32) ||
(charPositionX <= 0 && direction.x > 0) ||
(charPositionX >= canvas.width-32 && direction.x < 0))
charPositionX += direction.x;
}
if (direction.y){
if ((charPositionY > 0 && charPositionY < canvas.height-32) ||
(charPositionY <= 0 && direction.y > 0) ||
(charPositionY >= canvas.width-32 && direction.y < 0))
charPositionY += direction.y;
}
// finally draw ou character
draw();
// update the raf id
raf = requestAnimationFrame(move);
};
// let's go !
raf = requestAnimationFrame(move);
}
draw();
window.addEventListener('keydown', triggerMoveChar, true);
window.addEventListener('keyup', releaseMoveChar, true); canvas {
margin: auto;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
border: 3px solid red;
}
body {
background: #222;
}
.container {
color: #999;
margin: 0;
padding: 10px 0px 20px;
font-family: "Orbitron", "Helvetica", sans-serif;
text-align: center;
font-size: 11px;
line-height: 16px;
}
.container h1 {
margin: 10px 0;
color: red;
font-size: 32px;
min-height: 430px;
}
.container h2 {
margin: 10px 0;
color: #ccc;
font-size: 24px;
min-height: 10px;
}
.container h3 {
margin: 10px 0;
color: #999;
font-size: 18px;
} <div class = "container">
<canvas id = "canvas" width = "640" height = "416"></canvas>
<h1>Project : Simple Game [v0.1alpha]</h1>
<h2>CONTROLS: </h2>
<h3>Arrow Keys </h3>
</div> Я буду признателен за любую помощь.
Извините, что вопрос был неясен для вас, @hindmost, но, как говорится во втором абзаце, «Проблема, с которой я сталкиваюсь, заключается в том, что всякий раз, когда я делаю значение ширины холста больше, чем высота, квадрат застревает после достижения внизу страницы». Проблема заключалась в том, что квадрат застревал внизу страницы при попытке сделать значение ширины холста больше, чем значение высоты. Спасибо, что заглянули.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


У вас опечатка в этой строке
if (direction.y){
if ((charPositionY > 0 && charPositionY < canvas.height-32) ||
(charPositionY <= 0 && direction.y > 0) ||
(charPositionY >= canvas.width-32 && direction.y < 0)) // here
charPositionY += direction.y;
}
Должно быть height, а не width.
(charPositionY >= canvas.height-32 && direction.y < 0))
Большое спасибо! Не знаю, как я это пропустил :D
Из сообщения неясно, является ли «застревание» вашей проблемой или желаемым результатом.