var canvas = document.getElementById("c1"),
ctx = canvas.getContext("2d"),
width = 400,
height = 400,
player = {
x: 200,
y: 200,
width: 10,
height: 10
},
keys = [];
canvas.width = width;
canvas.height = height;
var block = {
width: 25,
height: 25,
x: 300,
y: 300
};
function update() {
if (keys[38] || keys[32]) {
player.y -= 5;
}
if (keys[39]) {
player.x += 5;
}
if (keys[37]) {
player.x -= 5;
}
if (keys[40]) {
player.y += 5;
}
if (player.width + player.x > 400) {
player.x -= 5;
}
if (player.width + player.x < 10) {
player.x += 5;
}
if (player.height + player.y < 10) {
player.y += 5;
}
if (player.height + player.y > 400) {
player.y -= 5;
}
if (player.x < block.x + block.width && player.x + player.width >
block.x &&
player.y < block.y + block.height && player.y + player.height >
block.y) {
console.log("The objects are touching");
player.y = player.y - 7;
}
ctx.beginPath();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "red";
ctx.fillRect(player.x, player.y, player.width, player.height);
ctx.beginPath();
ctx.fillStyle = "blue";
ctx.fillRect(block.x, block.y, block.width, block.height);
function gravity() {
if (player.y < 390) {
player.y = player.y + 2;
}
}
requestAnimationFrame(update);
requestAnimationFrame(gravity);
}
document.body.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
keys[e.keyCode] = false;
});
window.addEventListener("load", function() {
update();
});
canvas {
border: 1px solid black;
}
body {
margin 0;
}
<canvas id="c1" width="400" height="400"></canvas>