【Babylonjs】基本の動作をPlaygroundで作成したのでまとめました

updated 2022-4-29

キー操作による移動

// You have to create a function called createScene. This function must return a BABYLON.Scene object
// You can reference the following variables: engine, canvas
// You must at least define a camera

var createScene = function() {
    var scene = new BABYLON.Scene(engine);

    //var camera = new BABYLON.ArcRotateCamera("Camera", -Math.PI / 2, Math.PI / 2, 12, BABYLON.Vector3.Zero(), scene);
    var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);

    // This targets the camera to scene origin
    camera.setTarget(BABYLON.Vector3.Zero());

    // This attaches the camera to the canvas
    // camera.attachControl(canvas, true);

    let box = new BABYLON.MeshBuilder.CreateBox("box", {}, scene);
    let boxMaterial = new BABYLON.StandardMaterial("box-color", scene);
    boxMaterial.diffuseColor = new BABYLON.Color3(1, 0, 1);
    box.material = boxMaterial;
    let ground = new BABYLON.CreateGround("ground", { width: 10, height: 10 });
    ground.position.y = 0;
    let light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);

    let player = scene.getMeshByName("box");

    scene.onKeyboardObservable.add((key) => {
        switch(key.type) {
            case BABYLON.KeyboardEventTypes.KEYDOWN:
                switch(key.event.code) {
                    case "ArrowRight": 
                        player.movePOV(-1, 0, 0);
                        console.log(player.position);
                        break;
                    case "ArrowLeft":
                        player.movePOV(1, 0, 0);
                        console.log(player.position);
                        break;
                }
                break;
        }
    });

    return scene;
};