Asher
Asher

Reputation: 1

Javascript collsion detection

Hi I am new to this forum and new to JavaScript programming and I would like to know why my collision detection is not working. I would not like to use any library like JQuery, I just want it to work with pure JavaScript. Thank you for your help here is the code

var can = document.getElementById("mainCanvas");
var ctx = can.getContext("2d");
var player1 = {x:"20", y:"20", w:"20", h:"20"};
var enemy1 = {x:"50", y:"50", w:"20", h:"20"};
ctx.fillRect(player1.x,player1.y,player1.w,player1.h);
ctx.fillRect(enemy1.x,enemy1.y,enemy1.w,enemy1.h);
//right arrow moves block right
window.addEventListener("keydown",function(e){
if(e.keyCode==39){
     ctx.clearRect(player1.x,player1.y,player1.w,player1.h);
     player1.x++;
     ctx.fillRect(player1.x,player1.y,player1.w,player1.h);
}});
//left arrow moves block left
window.addEventListener("keydown",function(e){
if(e.keyCode==37){
     ctx.clearRect(player1.x,player1.y,player1.w,player1.h);
     player1.x--;
     ctx.fillRect(player1.x,player1.y,player1.w,player1.h);
}});
//up arrow makes block up
window.addEventListener("keydown",function(e){
if(e.keyCode==38){
     ctx.clearRect(player1.x,player1.y,player1.w,player1.h);
     player1.y--;
     ctx.fillRect(player1.x,player1.y,player1.w,player1.h);
}});
//down arrow makes block go down
window.addEventListener("keydown",function(e){
if(e.keyCode==40){
     ctx.clearRect(player1.x,player1.y,player1.w,player1.h);
     player1.y++;
     ctx.fillRect(player1.x,player1.y,player1.w,player1.h);
}});

if(player1.x == enemy1.x && player1.y == enemy1.y){
alert("touch");
}

Upvotes: 0

Views: 87

Answers (1)

Kazetsukai
Kazetsukai

Reputation: 2258

I agree with Micah, you should probably use an existing physics engine.

However the reason your collision detection code is not working is that it doesn't take into account the width and height of the enemy and player. At the moment it will only trigger when the player and enemy are COMPLETELY on top of each other (for example the pixel in the top left corner of each of them is touching).

What you need instead of if (player1.x == enemy1.x && player1.y == enemy1.y) is something like: if (player1.x + player1.w > enemy1.x && player1.x < enemy1.x + enemy1.w && player1.y + player1.h > enemy1.y && player1.y < enemy1.y + enemy1.h)

which checks if the player and the enemy are overlapping on any side.

Upvotes: 1

Related Questions