Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character Movement using Babylon.js

In a game demo I am putting up for school I need to move my character using the W-A-S-D keys and also the arrow keys. I put up a function and set up a switch case to listen for any of the key presses. Here is my code snippet:

//Handles the player's movement
var PlayerMovement = (function () {
    //Constructor
    function PlayerMovement() {
        this.gameObject = null;
        this.movementSpeed = 0;
        this.rotationSpeed = 0;
    }

    PlayerMovement.prototype.awake = function () {
        console.log("Awake");
    };

    PlayerMovement.prototype.update = function () {
        //console.log(Tools.getFps());
    }

PlayerMovement.prototype.onKeyPressed = function (key) {
        switch(key)
        {
            case KeyType.W:
            case KeyType.UpArrow:
                console.log("Moving up");
                this.gameObject.meshObject.position.z += (BABYLON.Vector3.Up() * this.movementSpeed * Tools.getDeltaTime());
                break;
            case KeyType.A:
            case KeyType.LeftArrow:
                //TODO: Do stuff
                break;
            case KeyType.S:
            case KeyType.DownArrow:
                //TODO: Do stuff
                break;
            case KeyType.D:
            case KeyType.RightArrow:
                //TODO: Do stuff
                break;
        }
    }
 return PlayerMovement;
})();

My issue is that my character jumps so far ahead that he vanishes from the screen. Can anyone help me figure out what is wrong with my calculation?

like image 662
user3838697 Avatar asked Sep 30 '22 04:09

user3838697


1 Answers

A few things -

  • BABYLON.Vector3.Up() is (0,1,0) . Multiplying this object with any number will return NaN. I guess the object doesn't jump away from the screen, it simply disappears.
  • Z is not up :-) position.y should be changed if you wish to jump up.
  • If you want to translate using vectors (using the BABYLON.Vector3.Up() Vector) use the mesh.translate(vector, distance) function. In your case (assuming this is the right value you want to set):

    this.gameObject.meshObject.translate(BABYLON.Vector3.Up(), this.movementSpeed * Tools.getDeltaTime());
    
  • I assume you did that already, but if not - turn the physics engine on and set gravity for your scene. You can learn about it in the BJS Docs : http://doc.babylonjs.com/page.php?p=22091

  • A better way to implement a jump would be to apply acceleration in the right direction (up) and letting the physics engine do its magic. Check out "Applying impulse" here - http://blogs.msdn.com/b/eternalcoding/archive/2013/12/19/create-wonderful-interactive-games-for-the-web-using-webgl-and-a-physics-engine-babylon-js-amp-cannon-js.aspx

like image 126
Raanan W Avatar answered Oct 01 '22 20:10

Raanan W