First Person Jump Movement

I am using the sample code from the tutorial for First Person Movement. I tried to add a jump feature to it by adding this code:

if (app.keyboard.isPressed(pc.KEY_SPACE)) {
    y += forward.y;

I also added y as a variable here: // movement var x = 0; var z = 0; var y = 0;
And a couple other changes, like here (I bolded by change):

if (x !== 0 && z !== 0 && y !== 0) {
    force.set(x, y, z).normalize().scale(this.power);

And yet, this doesn’t work. When I press space, nothing happens. Is it even possible to have the camera/player jump?

It sounds like you want applyImpulse which immediately gives the rigidbody instant acceleration.

applyForce only applies acceleration for the frame that it has been used. Eg Gravity is a force that is applied every frame.

So then what do I need to change?

With the x and z force is being applied every frame to create the movement. With the way you are applying force to y, you would need to hold the button like you do the movement keys. If you want it to jump on press, remove the y variable from force.set() and use impulse for it instead. Impulse immediately applies the desired force to the rigidbody, while using force applies a small amount over time. The applied impulse would also have to be greater than the gravity in scene (default -9.8).

Okay, now look at this:
When you press space, the screen turns completely grey.

You applying impulse on the negative Y which is downwards. Chances are that you are seeing your player go through the floor.

I made the y it positive and it still turns grey.

I copy pasted the code from the tutorial again, then added the if statement. Now space doesn’t do anything.

For me it does exactly what I said applying force would do, the fps character starts to float while I hold space. One thing I may suggest to fix this, is to check if the player is grounded.
This is how I would go about it:

FirstPersonMovement.prototype.initialize = function() {
//Code here//
    this.grounded = true;

 //Code here//

FirstPersonMovement.prototype.update = function(dt) {
//Code here
    var pos = this.entity.getPosition();
    //Code here//

    if (app.keyboard.isPressed(pc.KEY_SPACE)) {
        if(this.grounded) {
            this.entity.rigidbody.applyImpulse(0, 200, 0);
    if(pos.y > 1.2) {
        this.grounded = false;
    else {
        this.grounded = true;
//Code here//

My fork.

Thank you so much!
This is really helpful.

1 Like

Not a problem. You’re welcome.