How do I fix my code?
At the moment my character goes up for as long as you hold the up key. I want a more jump like effect where the character will drop back down when it reaches a certain height. I want the character to only be able to jump again once it's fallen back down.
Below is my code so far.
var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext("2d");
var keys = [];
var width = 500, height = 400, speed = 4;
var score = 0;
var player = {
x: 40,
y: 350,
width: 20,
height: 20,
gravity: 20,
weight: 1
};
window.addEventListener("keydown", function(e){
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e){
delete keys[e.keyCode];
}, false);
function game(){
update();
render();
}
function update(){
if(keys[38]) player.y-=speed;
if(speed < player.gravity) player.y+=player.weight;
if(player.x < 0) player.x = 0;
if(player.y < 0) player.y = 0;
if(player.x >= width - player.width) player.x = width - player.width;
if(player.y >= height - player.height) player.y = height - player.height;
}
function render(){
context.clearRect(0,0,width,height);
context.fillStyle = "blue";
context.fillRect(player.x, player.y, player.width, player.height);
setInterval(function(){
game();
}, 1000/60)
}