Skip to content
On this page

Camera

The goal of this section of the tutorial will be to enable camera movement.

Setup

  1. To get things setup make a empty gameObject inside the root gameObject and rename it to cameraController. This can be done by right clicking on the root gameObject in the tree view and clicking on Create new empty child. To rename this child click on the pencil icon that shows up when howering over the gameObject in the tree view. cameraController

  2. Make the camera a child of cameraController by cuting it and pasting it insider the cameraController cameraChild

  3. Update the camera position to [0,0,30] and rotation to [0,0,0] positionedCamer

  4. Add a transfrom component to the cameraController transformOnCameraController

  5. Repostion the cameraController to [0,8,0] renameTransfomr

  6. Update the transform component name from 'newRef' to 'transform' renameTransfomr

Writing the movement logic

  1. Create the file <ProjectRoot>/src/scripts/camera.ts. This file will contain the logic for the camera movement.

  2. Upade this file with the following script that looks at the mouse position and updates the rotation on the transform for the camera controller.

TypeScript
export const init = (game, gameObject) => {
   
    window.addEventListener('mousemove', e => {

        // get mouse x position ( normalized -1 to 1 )
        const x = 2 * ((e.clientX / window.innerWidth) - 0.5 );
        // get mouse y position ( normalized -1 to 1 )
        const y = 2 * ((e.clientY / window.innerHeight) - 0.5);

        const transform = gameObject.components.transform;
        if(!transform)return;//return if transform is not initialized

        //update transform rotation
        transform.rotation.x = (Math.PI / -3) * y;
        transform.rotation.y = (Math.PI / -3) * x;
    })
}

In the above script the gameObject will be the cameraController (because this script will be attached to the camera controller).

  1. Add this script to the cameraController, by first adding a script component to the cameraController, script

and then setting the value of the gameScript prop to the absolute scrip path(absolute from the root of the project), ie. /src/scripts/camera.ts. scriptPath

At this point you should see the camera move.

Lighting (optional)

At the moment there is a single light attached to the camera, which is non ideal because the camera is non stationary, so in this section we will correct this.

  1. Delete the light component on the camera. deleteLight

At this point if you disable editor lighting, you will see that there are no lights anywhere so all the meshes turn black. Disabling ambient and directional lighting in the editor gives a view which is closer to what the game will look like. editorView

  1. Add 2 lights on the cameraController and make one of them ambient. addLight