Hi I’m trying to create a game. I have a vacuum cleaner that moves side to side and up and down.
My problem: When I move it to far off to the side it will go completely off screen. How can I make a boundary to keep it on screen? I have never tried to make anything like this so I’m not really sure how to handle this problem yet.
What I tried :
function leftBounds() {
if(parseInt(vacuum.style.left) > 0) {
vacuum.style.left = parseInt(vacuum.style.left, 10) - 10 + 'px';
}
}
leftBounds();
Complete code :
window.onload = docReady();
var vacuum = document.getElementById('vacuum');
var spaceKey = 32;
var leftKey = 37;
var rightKey = 39;
var fired = false;
var screenWidth = window.innerWidth;
var vacWidth = document.getElementById('vacuum').offsetWidth;
function setPosition(element, x, y){
element.style.left = x + 'px';
element.style.top = y + 'px';
}
function leftBounds() {
if(parseInt(vacuum.style.left) > 0) {
vacuum.style.left = parseInt(vacuum.style.left, 10) - 10 + 'px';
}
}
leftBounds();
function spaceReleased(evt) {
if(fired === true && evt.keyCode === spaceKey) {
fired = false;
vacuum.style.top = parseInt(vacuum.style.top) + 100 + 'px';
}
}
function VacuumUpAndDown(evt) {
if(fired === false && evt.keyCode === spaceKey) {
fired = true;
vacuum.style.top = parseInt(vacuum.style.top) - 100 + 'px';
}
console.log(evt.keyCode)
}
document.onkeydown = function(evt) {
if(evt.keyCode === leftKey) {
vacuum.style.left = parseInt(vacuum.style.left) - 20 + 'px'
}
if(evt.keyCode === rightKey) {
vacuum.style.left = parseInt(vacuum.style.left) + 20 + 'px'
}
}
window.addEventListener('keydown', VacuumUpAndDown);
window.addEventListener('keyup', spaceReleased);
function docReady(){
var vacuum = document.getElementById('vacuum');
setPosition(vacuum, 550, 415);
}

. This shows how to move in the X axis, but should help.