I am trying to make a canvas boundary for my mini-game. I have already created the canvas with a character that can move with the arrows. I used a switch statement to do this, the next step is to create a boundary and I am not sure how to go about that? This is how the Javascript Code looks at the moment:
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', keyPress);
}
function keyPress(e)
{
let x = e.keyCode;
let character = document.getElementById("character").getBoundingClientRect();
let canvasWidth = document.getElementById("canvas").getBoundingClientRect();
let left = parseInt(character.left,10);
let top = parseInt(character.top,10)
switch (x) {
//left
case 37:
place('character', left-15, top);
break;
//right
case 39:
place('character', left 15, top);
break;
//up
case 38:
place('character', left, top-15);
break;
//down
case 40:
place('character', left, top 15);
break;
}
console.log(x)
return x
}
update()
CodePudding user response:
I'm assuming the boundary you're talking about is a boundary for your character to move? If so...
You'll want to check in the keyPress method before moving your character.
Something like this:
First, I'd consider renaming canvasWidth
to something like canvasBound
, and similarly for your character bounds variable.
if (!(characterBound.left - 15 < canvasBound.left)) {
...move character left...
}
... else do nothing (don't have to actually include this)
repeat similarly for moving up, down, right, etc. You'll have to play with the values to get it right for your sprite.