Search code examples
javascriptbabylonjs

How to tell if Shift key is being held down


I am making a first-person game using Babylon.js and I'm trying to add a feature where the player can sprint (camera.speed is increased) when holding SHIFT, but SHIFT doesn't trigger the keydown event, so I was wondering if there is a way to add this trigger, either with Babylon or just with Javascript.


Solution

  • I ended up figuring it out. What I had to do was create an action manager attached to the scene, then add a trigger for when the shift key was pressed. Here's the final code:

    const scene.actionManager = new BABYLON.ActionManager(scene);
    scene.actionManager.registerAction(
        new BABYLON.ExecuteCodeAction({
            trigger: BABYLON.ActionManager.OnKeyDownTrigger,
            parameter: 16 // key code for shift
            }, () => {
                camera.speed = 0.8;
            },
            new BABYLON.PredicateCondition(scene.actionManager, () => {return camera.speed === 0.3}) // checks to see if it's already changed so it isn't setting the value every frame
        )
    );
            
    this.scene.actionManager.registerAction(
        new BABYLON.ExecuteCodeAction({
            trigger: BABYLON.ActionManager.OnKeyUpTrigger,
            parameter: 16
        }, () => {
            camera.speed = 0.3;
        })
    );
    

    This would also work for CTRL, if you wanted to use it for crouch or some other function, you would just change parameter: 17.