He estado tratando de descubrir cómo hacer que el personaje se detenga cuando golpea la pared derecha y la pared inferior del lienzo sin suerte. Consulte el código a continuación:
function place(id,x_pos, y_pos,) { let element = document.getElementById(id); element.style.position = "absolute"; element.style.left = x_pos + 'px'; element.style.top = y_pos + 'px'; } setInterval(update,1); function update() { document.addEventListener('keydown', keydown); } function keydown(e) { let x = e.keyCode; let character = document.getElementById("character").getBoundingClientRect(); let canvasbound = document.getElementById("canvas").getBoundingClientRect(); let left = parseInt(character.left,10); let top = parseInt(character.top,10); switch (x) { //left case 37: if(!(character.left-15 < canvasbound.left)) { place('character', left-15, top); } break; //right case 39: if(!(character.left+15 < canvasbound.left)) { place('character', left+15, top); } break; //up case 38: if(!(character.top-15 < canvasbound.top)) { place('character', left, top-15); } break; //down case 40: if(!(character.top+15 < canvasbound.down)) { place('character', left, top+15); } break; } console.log(x) return x }El caso 39 está destinado a permitir que el personaje viaje hasta que golpee la pared derecha y se detenga, pero atraviesa la pared:
case 39: if(!(character.left+15 < canvasbound.left)) { place('character', left+15, top); } break;Lo mismo para el caso 40, excepto que el personaje cae y pasa la pared que se supone que no debe hacer.
case 40: if(!(character.top+15 < canvasbound.top)) { place('character', left, top+15); } break;¿Hay algo que me falta? Estaba pensando que podría estar faltando algo en esta área del código:
function place(id,x_pos, y_pos,) { let element = document.getElementById(id); element.style.position = "absolute"; element.style.left = x_pos + 'px'; element.style.top = y_pos + 'px'; }Cuando se mueve a la derecha, está probando si el personaje pasa por el límite izquierdo (canvasbound.left), necesita cambiar eso para probar el límite derecho (canvasbound.right). Lo mismo para el límite inferior.
El código estaba un poco confundido sobre cuál tecla es cuál, y las condiciones eran difíciles de leer. como con x, y, izquierda, derecha, más, menos, <, > y !.
Aquí, el código se reorganiza un poco, separando las reglas sobre el movimiento de las restricciones y refiriéndose solo a los rectángulos delimitadores (sin constantes codificadas), para que sea duradero si el lienzo o el carácter cambian de tamaño.
function place(id, x_pos, y_pos, ) { let element = document.getElementById(id); element.style.position = "absolute"; element.style.left = x_pos + 'px'; element.style.top = y_pos + 'px'; } function init() { const bounds = document.getElementById("canvas").getBoundingClientRect(); place('character', 0, 0); document.addEventListener('keydown', keydown); } init(); function keydown(e) { let key = e.keyCode; const character = document.getElementById("character").getBoundingClientRect(); let dx = 0, dy = 0; // get x and y increments based on the key, don't worry about the bounds const rules = { 37: () => dx -= character.width, // left 38: () => dy -= character.height, // up 39: () => dx += character.width, // right 40: () => dy += character.height // down }; if (key in rules) rules[key](); // functions that clamp x,y to bounds const bounds = document.getElementById("canvas").getBoundingClientRect(); const clampX = x => Math.min(Math.max(x, bounds.left), bounds.right - character.width); const clampY = y => Math.min(Math.max(y, bounds.top), bounds.bottom - character.height); // increment the character position and clamp const newX = clampX(character.left + dx) const newY = clampY(character.top + dy) place('character', newX, newY); return key } html, body { margin: 0; } <div id="character" style="width:20px; height:20px; background-color:blue"></div> <canvas id="canvas" style="background-color:yellow;"></canvas>La idea más importante relacionada con el OP es la idea de "sujeción". Usamos esto todo el tiempo para hacer cumplir las restricciones de punto final. Siempre toma esta forma....
Math.min(upperLimit, Math.max(lowerLimit, someValue))