How to make character jump while walking?

Asked

Viewed 435 times

1

I am creating a game in Javascript. This is my first contact with the language and also the development of games.

Going straight to the question, I can walk and jump in the game, but when I’m walking and jumping, the game does not perform anything, stops walking and also does not jump (the game does not freeze, if you release the keys and press again it makes the functions of walking and jumping normally).

These functions check the pressed key and perform the function:

function jump(event){
        if(event.keyCode == 38){
            cube.pula();
        }
    }


function walk(){
        if(event.keyCode == 39){
            cube.right();
        }
        if(event.keyCode == 37){
            cube.left();
        }
    }

These are the functions (skip, right, left). The functions are inside an object called cube:

pula: function(event){
            if(this.jps < 2){
                this.jps++;
                this.v = -this.fp;
            }else if(this.y == 250){
                this.jps = 0;
                this.jps++;
                this.v = -this.fp;
            }
        },

        right: function(){
                if(this.x <= width-64){
                    this.x += this.force;
                }
        },


        left: function(){
            if(this.x >= 15){
                this.x += -this.force;
            }
        },

I put the code in Codepen as requested. I also put an html comment explaining the variables.

Codepen: https://codepen.io/toniotti/pen/MMJpeY

  • 2

    We need a little more information to help you, for example: Where are the functions called jump and walk? What do the variables mean jps, v, fp, force, And where are they being used? You can guess what they do, but it’s a lot easier if you explain, and the chances of being able to help you increase x)

1 answer

1

As it is your first contact with the language, I advise you to give a study on Debugger, or as most JS programmers who do gambiarra (as I haha), at least use the console.log to know what is happening.

For example, within each function, place a.log console with action information:

console.log('walk')
console.log('right')
console.log('left')
console.log('jump')

And also put a console.log('event.keyCode', event.keyCode). With this, you will probably see that the two keys have been pressed, just like in this example: https://franciscoprado.com.br/teclas-pressionadas-com-javascript-jquery/

What you can do is an if to walk + jump, and if not, that is, it did not jump, it only walked, you run only the jump Event.keycode is also active, and if so, call the function.

There is still little code to help you. It would be better if you put it on some site like codepen and make it available to help you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.