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?
A few things -
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With