%%html
<style>
#canvas {
margin: 0;
border: 1px solid white;
}
</style>
<canvas id="canvas"></canvas>
<script>
let canvas = document.getElementById('canvas');
let c = canvas.getContext('2d');
canvas.width = 650;
canvas.height = 300;
let gravity = 1.5;
class Player {
constructor() {
this.position = {
x: 100,
y: 100
};
this.velocity = {
x: 0,
y: 0
};
this.width = 30;
this.height = 30;
}
draw() {
c.fillStyle = 'red';
c.fillRect(this.position.x, this.position.y, this.width, this.height);
}
update() {
this.draw();
this.position.y += this.velocity.y;
this.position.x += this.velocity.x;
if (this.position.y + this.height + this.velocity.y <= canvas.height)
this.velocity.y += gravity;
else
this.velocity.y = 0;
}
}
class Platform {
constructor(image) {
this.position = {
x: 0,
y: 200
}
this.image = image;
this.width = 540;
this.height = 160;
}
draw() {
c.drawImage(this.image, this.position.x, this.position.y);
}
}
let image = new Image();
let platform = new Platform(image);
player = new Player();
let keys = {
right: {
pressed: false
},
left: {
pressed: false
}
}
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, canvas.width, canvas.height);
platform.draw();
player.update();
if (keys.right.pressed && player.position.x + player.width <= canvas.width - 50) {
player.velocity.x = 15;
} else if (keys.left.pressed && player.position.x >= 50) {
player.velocity.x = -15;
} else {
player.velocity.x = 0;
}
if (
player.position.y + player.height <= platform.position.y &&
player.position.y + player.height + player.velocity.y >= platform.position.y &&
player.position.x + player.width >= platform.position.x &&
player.position.x <= platform.position.x + platform.width
)
{
player.velocity.y = 0;
}
}
animate();
addEventListener('keydown', ({ keyCode }) => {
switch (keyCode) {
case 65:
console.log('left');
keys.left.pressed = true;
break;
case 83:
console.log('down');
break;
case 68:
console.log('right');
keys.right.pressed = true;
break;
case 87:
console.log('up');
player.velocity.y -= 20;
break;
}
});
addEventListener('keyup', ({ keyCode }) => {
switch (keyCode) {
case 65:
console.log('left');
keys.left.pressed = false;
break;
case 83:
console.log('down');
break;
case 68:
console.log('right');
keys.right.pressed = false;
break;
case 87:
console.log('up');
player.velocity.y = -20;
break;
}
})
image.src = 'https://samayass.github.io/samayaCSA/images/platform.png'
</script>