Switching states

4.2
(5)
Created on September 03, 2019, Last modified on May 19, 2022

You can switch states with this._setState('MyStateName'). Below an example with a blue and green cube to visualize how switching states works in practice.

Press left or right to swap between the states of the blue and green cube.

class BasicUsageExample extends lng.Application {
    static _template() {
        return {
            ExamplanationText:{ x: 50, y: 28, text:{ text: 'Press left for MyBlueState,\n press right for MyGreenState \n', fontSize: 22, wordWrap: true, wordWrapWidth: 450, lineHeight: 30 }},
            MyBlueCube:{
               x: 100, y: 200, w: 100, h: 100, rect: true, color: 0xFF0034DD
            },
            MyGreenCube:{
               x: 400, y: 200, w: 100, h: 100, rect: true, color: 0xFF24DD00
            }
        }
    }
    
    _handleLeft(){
        this._setState('MyBlueState');
    }
    
    _handleRight(){
        this._setState('MyGreenState');
    }
    
    _init(){
        this._blueCubeAnimation = this.tag('MyBlueCube').animation({
            duration: 3, repeat: -1, stopMethod: 'immediate',
            actions: [{ p: 'rotation', v: { 0: { v: 0, sm: 0 }, 1: { v: -Math.PI * 2, sm: 0 } } }]
        });
        this._greenCubeAnimation = this.tag('MyGreenCube').animation({
            duration: 3, repeat: -1, stopMethod: 'immediate',
            actions: [{ p: 'rotation', v: { 0: { v: 0, sm: 0 }, 1: { v: Math.PI * 2, sm: 0 } } }]
        });
    }
        
    static _states(){
        return [
             class MyBlueState extends this{
                $enter(event){
                    this._blueCubeAnimation.play();                    
                }
                $exit(){
                    this._blueCubeAnimation.pause();
                }                            
            },
            class MyGreenState extends this{
                $enter(){
                    this._greenCubeAnimation.play();
                }
                $exit(){
                    this._greenCubeAnimation.pause();
                }
            }
        ];
    }
}

const app = new BasicUsageExample({stage: {w: window.innerWidth, h: window.innerHeight, useImageWorker: false}});
document.body.appendChild(app.stage.getCanvas());

Give feedback

Rating - 4.2 / 5. . Reviews - 5

No votes so far! Be the first to rate this post.

Go To Top