How to create a boundary area

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);
    

}


    


    

















Still looking for a little help.

Hello!

Just check the position of the vacuum and update accordingly when you reach the boundaries. Take into account the width of the vacuum when you’re moving right: vacuumWidth + speed cannot be greater than the screen width.

The same applies to the vacuum moving from top to bottom, but in this case you have to account for the height instead: vacuumHeight + speed cannot be bigger than the screen height.

I made this sample which may help you :slight_smile:. This shows how to move in the X axis, but should help.

Regards and happy coding!