I'm currently working on a little platform game. But it's not going really well with the collision detection. I've looked at many tutorials on this but is can't seem to understand it. Here's my code:
var ctx = document.getElementById("canvas").getContext("2d");
var rightPressed =false;
var spacePressed =false;
var leftPressed=false;
var gravity = 1;
//Player object
var player = {
x:50,
y:370,
dy:0,
dx:0,
width:10,
height:10,
speed:10,
jumping:false
};
//Box object
var box ={
x:200,
y:350,
width:50,
height:50
};
document.addEventListener("keydown", keyDown);
document.addEventListener("keyup", keyUp);
function keyDown(e) {
if(e.keyCode ==39){
rightPressed=true;
}
if (e.keyCode ==32){
spacePressed=true;
}
if (e.keyCode ==37){
leftPressed =true;
}
}
function keyUp(e) {
if(e.keyCode ==39){
rightPressed=false;
}
if (e.keyCode ==32){
spacePressed=false;
}
if (e.keyCode ==37){
leftPressed =false;
}
}
//Draw the ball
function drawBall(){
ctx.beginPath();
ctx.arc(player.x,player.y,10,0,Math.PI*2);
ctx.fillStyle="red";
ctx.fill();
}
//Draw the box
function drawBox() {
ctx.fillRect(box.x,box.y,box.width,box.height);
}
//The main function that calls the other functions and handles the logic
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
drawBall();
drawBox();
if (rightPressed){
//Right speed of the ball
player.x+=5;
}
if(leftPressed){
//Left speed of the ball
player.x-=5;
}
if(spacePressed){
if(!player.jumping){
//The hight of the jump
player.dy=-player.speed * 2;
player.jumping = true;
}
}
player.dy+=gravity;
player.x+=player.dx;
player.y+=player.dy;
if(player.y >= 390){
player.y = 390;
player.jumping = false;
}
//Box collision logic
window.requestAnimationFrame(draw)
}
window.requestAnimationFrame(draw);
canvas {border:1px solid black;}
<canvas id="canvas" width="400px" height="400px"> </canvas>
if (player.x+(player.width/2) >= box.x) {console.log("collision!");}