Canvas Bootcamp 19 – Collision Detection Hit Game Enemies JavaScript



Lesson Code: http://www.developphp.com/video/JavaScript/Collision-Detection-Hit-Game-Enemies
Learn object collision detection on the canvas with JavaScript for games and more. Along with a few other useful tactics included. Collision detection is the act of detecting when specific objects come into contact with one another and then programming some resulting effect of that collision. We are going to be putting the logic into a video game programming scenario to best demonstrate detecting collisions for multiple objects simultaneously. All of the code used in the basic application is code from all of the previous exercises.

source

25 thoughts on “Canvas Bootcamp 19 – Collision Detection Hit Game Enemies JavaScript”

  1. thanks a bunch for these lessons, but i had to take this lesson out of the OOP structured code.

    <!DOCTYPE html>
    <html lang ="en">

    <head>
    <meta charset="UTF-8">

    <title>star fire obj stars</title>
    <style type = "text/css">
    body{
    margin :0px;
    padding:0px;
    }

    #funcbuttons, #ctrlbuttons
    {display:table;float: left;
    list-style: horizontal;
    border:1px solid black; background:red;

    }

    button{display:table-cell;float:left;
    text-align:center;
    border:1px solid black;
    font: 17px tahoma;}

    #canvas{border: 1px solid; }

    </style>

    <script>

    function initCanvas(){
    var ctx = document.getElementById('canvas').getContext('2d');

    var cw= canvas.width, ch = canvas.height;
    var rmods= .05,anrt = 30;
    var x1 = 1, x2= 1, y1 = 2, y2= 1,vx =1,vy =1;
    var ax=1,ay= 1, x = 1, y = 1, stc= 1,dir;

    var unumcolor=["#DC143C", "#8A2BE2" , "#4169E1", "#FFE4E1", "#9400D3", "#F0FFFF" , "#483D8B","#333", "#b95e1c",
    "#9964CC","#FFA07A" ,"#DB7093", "pink", "#6495ED" , "black", "white",
    "#A0522D" ,"#006400" , "#CD853F", "#8FBC8F" ,"#008B8B" ,"#00CED1", "#1E90FF","magenta", "#4682B4" ,
    "#9DCEFF","#B0C4DE", "#FFFFF0" ,
    "green", "brown", "#4169E1", "red", "purple", "#b95e1c", "gray", "#DB7093", "#A0522D" ,"#FFE4E1" ];
    var mypic = new Image();
    mypic.src = "pict.jpeg";

    var clr = 2,mx=1,my=1,mw,mh, angle= 1, clr1 = 1;
    var animateInterval, j, m, e, i;

    var ene=[
    {"id":"ene1","ex":100,"ey":0,"ew":10,"eh":20}];
    var msles= [{"mx":x +5,"my":y, "mw":3,"mh":10}];//new Array();
    var Fxp= [];//new Array();
    var Fyp= [];//new Array();
    var y=450,x = 100,
    w= 50, h =25, dir; //var bg="orange";

    var mX,mY;
    //contrl buttns
    var Lmove= document.getElementById('Lmove');
    var Rmove= document.getElementById('Rmove');
    var Fire= document.getElementById('Fire');
    var uprite= document.getElementById('uprite');
    var upleft= document.getElementById('upleft');
    var str8up= document.getElementById('str8up');
    var dwnrite= document.getElementById('dwnrite');
    var dwnleft= document.getElementById('dwnleft');
    var str8dwn= document.getElementById('str8dwn');

    Fire.addEventListener('mousedown', function(event)
    {//dir = "fire";
    msles.push({"mx":x +5,"my":y, "mw":3,"mh":10});

    });//end fire push msles

    Lmove.addEventListener('mousedown', function(event)
    {dir = "left";});

    Lmove.addEventListener('mouseup', function(event)
    {dir = "";});

    Rmove.addEventListener('mousedown', function(event)
    {dir = "right";});

    Rmove.addEventListener('mouseup', function(event)
    {dir = "";});

    // up n dwn
    uprite.addEventListener('mousedown', function(event)
    {dir = "upr";});

    uprite.addEventListener('mouseup', function(event)
    {dir = "";});

    upleft.addEventListener('mousedown', function(event)
    {dir = "upl";});

    upleft.addEventListener('mouseup', function(event)
    {dir = "";});

    //

    dwnrite.addEventListener('mousedown', function(event)
    {dir = "dwnr";});

    dwnrite.addEventListener('mouseup', function(event)
    {dir = "";});

    dwnleft.addEventListener('mousedown', function(event)
    {dir = "dwnl";});

    dwnleft.addEventListener('mouseup', function(event)
    {dir = "";});

    str8up.addEventListener('mousedown', function(event)
    {dir = "up";});

    str8up.addEventListener('mouseup', function(event)
    {dir = "";});

    str8dwn.addEventListener('mousedown', function(event)
    {dir = "dwn";});

    str8dwn.addEventListener('mouseup', function(event)
    {dir = "";});

    // end contrl buttns
    //onmousemove down
    canvas.addEventListener('mousemove', function(event) {
    mX = event.clientX – ctx.canvas.offsetLeft;
    mY = event.clientY – ctx.canvas.offsetTop;

    //statpos
    if(mX >= 1 && mX < cw && mY >= 1 && mY < ch){
    document.getElementById('status').innerHTML = mX+" xy "+ mY;

    //document.getElementById('position').innerHTML = mX+" x/y "+mY;

    //ctx.fillText(mX+" x/y "+mY,mX,mY,150);
    //ctx.fillRect(mX,mY, 20,20);
    //msles.push({"mx":x + 5,"my":y, "mw":3,"mh":10});
    }

    });
    //end mousemove down

    function animate1(){

    //ctx.globalCompositeOperation="source-over";

    ctx.clearRect(0,0,cw,ch);
    ctx.drawImage(mypic,0,0,400,100);
    //whole thing inline non oop code
    // launcher

    if(dir == "left"){x -= 5 *stc;
    }

    if(dir == "right"){
    x += 5 *stc;
    }//end if esle
    if(dir == "up"){
    x += 0;y -= 5 *stc;
    }//end if up
    if(dir == "upr"){
    x += 5 *stc;y -= 5 *stc;
    }//end if upr
    if(dir == "upl"){
    x -= 5 *stc;y -= 5 *stc;
    }//end if upl

    if(dir == "dwn"){
    x += 0;y += 5 *stc;
    }//end if dwn

    if(dir == "dwnl"){
    x -= 5 *stc;y += 5 *stc;
    }//end if dwnl

    if(dir == "dwnr"){
    x += 5 *stc;y += 5 *stc;
    }//end if dwnr

    if(dir == "fire"){
    msles.push({"id":"ms1","mx":x+5,"my":y, "mw":5,"mh":10});

    }//end if fire
    ctx.fillStyle= "red";
    //restrian lacher
    if(x < 1){x= 10;}
    if(x > cw){x= cw -10;}
    if(y > ch + 10){y = ch +20;}
    if(y <20){y = 20;}

    ctx.drawImage(mypic,x,y,50,50);
    ctx.fillRect(x,y,20,20);
    // places launcher
    ctx.fillRect(mX,mY, 20,20);

    for(i = 0; i < msles.length; i++){
    m = msles[i];

    ctx.fillRect(m.mx,m.my -= 5, m.mw,m.mh);
    //mousmve msles
    //ctx.fillRect(mX,mY -= 5, m.mw,m.mh);
    if(m.my <20){msles.splice(i,1);

    //make burst

    x1= Math.floor((Math.random() * cw) + 1);
    ene.push({"id":x1,"ex":x1,"ey":0,"ew":50,"eh":20});

    }//splice out misles put ene

    }//end for msles loop
    //end msles

    // ene check hit dectect
    for(i =0; i<ene.length;i ++){
    e = ene[i];
    ctx.fillRect(e.ex,e.ey+=.5,e.ew,e.eh);
    ctx.drawImage(mypic,e.ex+100,e.ey+.5,50,50);
    if(m.mx +m.mw >= e.ex && m.mx <= e.ex+e.ew && m.my >= e.ey && m.my <= e.ey + e.eh){
    msles.splice(msles[m],1);//remove missiles
    ene.splice(i,1);// remove ene

    document.getElementById('hitstat').innerHTML = "you shot "+ e.id;

    x1= Math.floor((Math.random() * cw) + 1);
    ene.push({"id":x1,"ex":x1,"ey":0,"ew":50,"eh":20});

    }// endif hit dtct msles v ene

    //for mousemove launcher eraser/
    if(mX >= e.ex && mX <= e.ex+e.ew && mY >= e.ey && mY <= e.ey + e.eh){
    //msles.splice(msles[m],1);//remove missiles
    ene.splice(i,1);// remove ene

    document.getElementById('carstat').innerHTML = "you erased "+ e.id;

    x1= Math.floor((Math.random() * cw) + 1);
    ene.push({"id":x1,"ex":x1,"ey":0,"ew":20,"eh":20});

    }// endif hit dtct eraser
    // make ene stick to bottom
    }//end check for ene.legth
    }//end animte1
    animateInterval = setInterval(animate1,anrt);

    // Reload page on button click
    document.getElementById('doover').onclick = function(event) {
    window.location.reload(true);
    } // end reload page
    //clock speed stc fast
    document.getElementById('stcfast').onclick = function(event) {
    stc+= 1;
    document.getElementById('stcfast').innerHTML = "clock stc "+stc;

    }
    //clock speed

    //end amrate
    // canvas color changers
    document.getElementById('canvaswhite').onclick = function(event) {
    clr1= Math.floor((Math.random() * unumcolor.length) + 1);

    document.addEventListener('keydown',function(event){
    //var kp=String.fromCharCode(event.keyCode);

    if(event.keyCode === 32){//dir = "fire";
    msles.push({"mx":x + 5,"my":y, "mw":3,"mh":10});
    }

    //alert(event.keyCode + "is keycode for" +kp);
    if(event.keyCode === 87){dir = "up";}

    if(event.keyCode === 83){dir = " ";}

    if(event.keyCode === 65){dir = "left";}

    if(event.keyCode === 68){dir = "right";}

    if(event.keyCode === 81){dir = "upl";}

    if(event.keyCode === 69){dir = "upr";}

    if(event.keyCode === 90){dir = "dwnl";}

    if(event.keyCode === 88){dir = "dwn";}

    if(event.keyCode === 67){dir = "dwnr";}

    //alert(event.keyCode + "is keycode for" +kp);
    });
    //end control keybrd

  2. Here is the problem with your code, it doesn't really do much besides detect a collision. You cannot determine what side is hit, so if you want to make a more advanced game it doesn't work.

  3. you should also create a tutorial for drawing a pathway for jumping games, for example how to create a hilly map and make the player figure (lets say ball) interact with the ground, in this case the hill….Thats what I am trying to do in my game but I cannot find it anywhere.

  4. adam bro when i am setting the canvas same as that of the background of the webpage than a margin is left on left and top of the page is there any solution for this problem?

  5. Dear Adam, 
    i just wanted to thank you for excellent method of teaching, your kindness and knowledge of coding. i have never learnt from books, but learnt few books from high teachers like you.  Love and peace brings knowledge and the code of communication. 

Leave a Reply

Your email address will not be published. Required fields are marked *