Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

js how to know if element touch border

var update = function (modifier) {
    if (38 in keysDown) { // Player holding up
        hero.y -= hero.speed * modifier;
    }
    if (40 in keysDown) { // Player holding down
        hero.y += hero.speed * modifier;
    }
    if (37 in keysDown) { // Player holding left
        hero.x -= hero.speed * modifier;
    }
    if (39 in keysDown) { // Player holding right
        hero.x += hero.speed * modifier;
    }

    // Are they touching?
    if (
        hero.x <= (monster.x + 32)
        && monster.x <= (hero.x + 32)
        && hero.y <= (monster.y + 32)
        && monster.y <= (hero.y + 32)
    ) {
        ++monstersCaught;
        reset();
    }
    if(hero.x <= 0){
        hero.x = 0;
    }
    else if(isMaxWidth()){
        hero.x = canvas.width -32
    }
    if(hero.y <= 0){
        hero.y = 0;
    }
    else if(isMaxHeight()){
        hero.y = canvas.height -32
    }

};

var isMaxWidth = function(){
    return hero.x >= canvas.width - 32;
};

var isMaxHeight = function(){
    return hero.y >= canvas.height - 32;
};
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #js #element #touch #border
ADD COMMENT
Topic
Name
3+3 =