Camera
The goal of this section of the tutorial will be to enable camera movement.
Setup
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.Make the camera a child of cameraController by cuting it and pasting it insider the cameraController
Update the camera position to [0,0,30] and rotation to [0,0,0]
Add a
transfrom
component to the cameraControllerRepostion the cameraController to [0,8,0]
Update the
transform
component name from 'newRef' to 'transform'
Writing the movement logic
Create the file
<ProjectRoot>/src/scripts/camera.ts
. This file will contain the logic for the camera movement.Upade this file with the following script that looks at the mouse position and updates the rotation on the transform for the camera controller.
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).
- Add this script to the cameraController, by first adding a
script
component to the cameraController,
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
.
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.
- Delete the light component on the camera.
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.
- Add 2 lights on the cameraController and make one of them ambient.