Godogo
Godogo

Reputation: 27

Press the same key to do different actions

I wanna press the letter "L" to remove something and then press "L" again to add the thing that i removed. I can do the part that removes with this code:

  document.addEventListener("keydown", onDocumentKeyDown, false);

    function onDocumentKeyDown(event) {
        // Get the key code of the pressed key 
        var keyCode = event.which;
        console.log("l" + keyCode);
        if (keyCode == 76) {
            scene.remove(directionalLight);
        }

        render();
    }

I tried doing:

    else if (keyCode == 76) {
        scene.add(directionalLight);
    }

But obviously this doesn't work.

So how can i press the same key in order to do "scene.add(directionalLight);" ?

Upvotes: 0

Views: 110

Answers (2)

klonoa123
klonoa123

Reputation: 738

Try something like this:

//use a variable to keep track of if the directional light exists
bool light = true;

document.addEventListener("keydown", onDocumentKeyDown, false);

    function onDocumentKeyDown(event) {
        // Get the key code of the pressed key 
        var keyCode = event.which;
        console.log("l" + keyCode);
        if (keyCode == 76) {
            //check the status of the variable to decide what to do, 
            //and update its status
            if (light) {
                scene.remove(directionalLight);
                light = false;
            } else {
                scene.add(directionalLight);
                light = true;
            }
        }

        render();
    }

This is a pretty simple strategy for alternating between two behaviors.

Upvotes: 1

erics2783
erics2783

Reputation: 583

You would need another condition to check if the scene has been added or not. I'm not familiar with three.js, so I don't know if there's a variable you could check like scene.isAdded or not, but you can create your own. I created a variable called isAdded in the code below:

document.addEventListener("keydown", onDocumentKeyDown, false);

let isAdded = true; // define the variable outside of the function

function onDocumentKeyDown(event) {
    // Get the key code of the pressed key 
    var keyCode = event.which;
    console.log("l" + keyCode);
    if (keyCode == 76) {
        if (isAdded) {
            console.log('remove');
            scene.remove(directionalLight);
        } else {
            console.log('add');
            scene.add(directionalLight);
        }
        isAdded = !isAdded ; // toggle the isAdded variable
    }

    render();
}

Upvotes: 1

Related Questions