EJW
EJW

Reputation: 614

Why does a while loop, inside a threejs render function, not update every frame?

I have an array of 8 cubes, all 1px tall. When a button is hit, they are meant to tween to a new target height, using a while loop, like this:

if (buttonHit) {
    console.log('button hit')
    for (i in meshArray) {
        while (Math.abs(meshArray[i].scale.y - newList[i].cost)>5) {
            console.log(meshArray[3].scale.y)
            meshArray[i].scale.y += .3
        }
    }
    buttonHit = false;
}

What the console log shows me is that meshArray[3] holds at 1px 1215 times in a row, then adds .3, then stops, but the mesh just pops to it's target height once this is all done.

Does a while loop not work in the render()?

Upvotes: 0

Views: 637

Answers (1)

Chris Charles
Chris Charles

Reputation: 4446

The problem is that render is called once for each frame that needs to be rendered. You are doing all your changes in one frame. threejs never has a chance redraw anything.

What you need to do is change the height by .3 only once per call to render. Ie not have it in a loop.

something a bit like this:

function render() {

    if (buttonHit) {
        new_height = 2;
        buttonHit = false;
    }

    if (meshArray[i].scale.y < new_height) {
        meshArray[i].scale.y +=.3
    }

}

Upvotes: 1

Related Questions