0
\$\begingroup\$

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)
}
\$\endgroup\$
  • 1
    \$\begingroup\$ You should format your code, 4 spaces in front of a line will turn it into code. \$\endgroup\$ – test Nov 21 '14 at 3:31
1
\$\begingroup\$

You need to handle the player objects velocity vector i.e. it's speed and direction.
You also need gravity as a constant downward acting force.
Finally you also need to be able to detect if/when the object is standing on firm ground i.e. when they are able to jump (in this case it appears to be fairly straight forward matter of floor y = 0, i.e. if y==0 then object is on the floor, else it's in the air).

If the object is on the floor and the jump button is pressed, add the jump velocity vector, else, if it's in the air, add gravity vector.
On update move the object (barring any collisions) along it's velocity vector.

Trying to expand farther is proving to be beyond my writing abilities but there are countless excellent examples out there already for basic physics for games, for example
http://www.richardlord.net/presentations/physics-for-flash-games

| improve this answer | |
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.