Collision detection in javascript -


i implementing custom space invader in html/javascript. far works fine collision detection seems problem. after looking couple of solutions online, here have far.

my enemies represented in array this:

function logo(i){     = || {};     i.sprite = new image();     i.active = true;      i.width = 25;     i.height = 25;      i.explode = function(){         this.active = false;     }      i.draw = function(){         context.drawimage(i.sprite,this.x,this.y);     }      i.setres = function(name){         this.sprite.src = name;     }      return i; } 

which populated this:

var logoarray = [];     for(i=0;i<logodata.length;i++){         logoarray.push(logo({             x: logodata[i].x,             y: logodata[i].y         }));         logoarray[i].setres("./graphics/logo_slices/logo_" + logodata[i].name + ".png");         console.log(logoarray[i].sprite.src);     } 

the collision handled (enemy.explode this.active = false):

function handlecollision(){     playerbullets.foreach(function(bullet) {        logoarray.foreach(function(enemy) {           if (iscollide(bullet, enemy)) {             enemy.explode();             bullet.active = false;           }         });     }); }  function iscollide(a, b) {   return a.x < b.x + b.width &&          a.x + a.width > b.x &&          a.y < b.y + b.height &&          a.y + a.height > b.y; } 

the problem makes inactive left of impact point. understand quite hard depict problem happy clarify.

the draw function filters draw active elements of array:

logoarray.foreach(function(logo_slice){     logo_slice.draw(); }); 

thanks can give!

regarding collision logic, take opposite approach:

take 4 cases define not collide , negate them. being above, being below, being besides left / right. not being either of these 4 makes collision.

just guess reason. rest of "engine" looks reasonable , should work.

collide =   !(a.x + a.width < b.x ||   a.x > b.x + b.width ||    a.y + a.height < b.y||   a.y > b.y + b.height ) 

additionally define radius per entity participates in collisions , use intersection via radius. of course need center of entities work.

edit: more details , elaborate example of different collision detection approaches in js, see https://developer.mozilla.org/en-us/docs/games/techniques/2d_collision_detection.


Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -