### Importing Libraries and Initializing Application Source: https://github.com/mugen87/yuka/blob/master/examples/math/orientation/index.html Imports necessary modules from Yuka.js and Three.js, declares global variables for the 3D scene and game entities, and initiates the application by calling the `init` and `animate` functions. ```JavaScript import * as YUKA from '../../../build/yuka.module.js'; import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.109/build/three.module.js'; let renderer, scene, camera; let entityManager, time, entity, target; init(); animate(); ``` -------------------------------- ### Initializing Three.js Scene, Camera, and Renderer Source: https://github.com/mugen87/yuka/blob/master/examples/math/orientation/index.html Sets up the basic Three.js scene, configures a perspective camera with its position and look-at target, and initializes the WebGL renderer. The renderer is sized to the window and appended to the document body. ```JavaScript function init() { scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 0.1, 1000 ); camera.position.set( 0, 0, 10 ); camera.lookAt( scene.position ); renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); } ``` -------------------------------- ### Calling Initialization and Animation Functions Source: https://github.com/mugen87/yuka/blob/master/examples/steering/flee/index.html This snippet initiates the application by calling the `init()` function to set up the scene and game entities, followed by `animate()` to start the rendering loop. These calls are the entry point for the application's execution. ```JavaScript init(); animate(); ``` -------------------------------- ### Initializing YUKA and Three.js Environment Source: https://github.com/mugen87/yuka/blob/master/examples/steering/arrive/index.html This snippet handles the initial setup of the 3D scene using Three.js and initializes the YUKA simulation components. It creates a vehicle and a target, applies the 'ArriveBehavior' to the vehicle, and adds them to the entity manager for simulation. ```JavaScript import * as YUKA from '../../../build/yuka.module.js'; import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.109/build/three.module.js'; let renderer, scene, camera; let entityManager, time, vehicle, target; init(); animate(); function init() { scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 0.1, 1000 ); camera.position.set( 0, 0, 10 ); camera.lookAt( scene.position ); // const vehicleGeometry = new THREE.ConeBufferGeometry( 0.1, 0.5, 8 ); vehicleGeometry.rotateX( Math.PI * 0.5 ); const vehicleMaterial = new THREE.MeshNormalMaterial(); const vehicleMesh = new THREE.Mesh( vehicleGeometry, vehicleMaterial ); vehicleMesh.matrixAutoUpdate = false; scene.add( vehicleMesh ); const targetGeometry = new THREE.SphereBufferGeometry( 0.05 ); const targetMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000 } ); const targetMesh = new THREE.Mesh( targetGeometry, targetMaterial ); targetMesh.matrixAutoUpdate = false; scene.add( targetMesh ); // const sphereGeometry = new THREE.SphereBufferGeometry( 2, 32, 32 ); const sphereMaterial = new THREE.MeshBasicMaterial( { color: 0xcccccc, wireframe: true, transparent: true, opacity: 0.2 } ); const sphere = new THREE.Mesh( sphereGeometry, sphereMaterial ); scene.add( sphere ); renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); // window.addEventListener( 'resize', onWindowResize, false ); // game setup entityManager = new YUKA.EntityManager(); time = new YUKA.Time(); target = new YUKA.GameEntity(); target.setRenderComponent( targetMesh, sync ); vehicle = new YUKA.Vehicle(); vehicle.setRenderComponent( vehicleMesh, sync ); const arriveBehavior = new YUKA.ArriveBehavior( target.position, 2.5, 0.1 ); vehicle.steering.add( arriveBehavior ); entityManager.add( target ); entityManager.add( vehicle ); generateTarget(); } ``` -------------------------------- ### Setting Up Three.js Scene, Camera, Ground, and Lighting - JavaScript Source: https://github.com/mugen87/yuka/blob/master/examples/fsm/index.html This part of the 'init' function configures the basic Three.js environment. It initializes the scene with a background color and fog, sets up a perspective camera, creates a ground plane with a Phong material, and adds a directional light source to cast shadows, preparing the visual space for the game entities. ```JavaScript scene = new THREE.Scene(); scene.background = new THREE.Color( 0xa0a0a0 ); scene.fog = new THREE.Fog( 0xa0a0a0, 20, 40 ); camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 200 ); camera.position.set( 0, 2, - 4 ); // const geometry = new THREE.PlaneBufferGeometry( 150, 150 ); const material = new THREE.MeshPhongMaterial( { color: 0x999999, depthWrite: false } ); const ground = new THREE.Mesh( geometry, material ); ground.rotation.x = - Math.PI / 2; ground.matrixAutoUpdate = false; ground.receiveShadow = true; ground.updateMatrix(); scene.add( ground ); // const hemiLight = new THREE.HemisphereLight( 0xffffff, 0x444444, 0.6 ); hemiLight.position.set( 0, 100, 0 ); hemiLight.matrixAutoUpdate = false; hemiLight.updateMatrix(); scene.add( hemiLight ); const dirLight = new THREE.DirectionalLight( 0xffffff, 0.8 ); dirLight.position.set( - 4, 5, - 5 ); dirLight.matrixAutoUpdate = false; dirLight.updateMatrix(); dirLight.castShadow = true; dirLight.shadow.camera.top = 2; dirLight.shadow.camera.bottom = - 2; dirLight.shadow.camera.left = - 2; dirLight.shadow.camera.right = 2; dirLight.shadow.camera.near = 0.1; dirLight.shadow.camera.far = 20; scene.add( dirLight ); ``` -------------------------------- ### Setting Up Yuka.js Game Entities Source: https://github.com/mugen87/yuka/blob/master/examples/math/orientation/index.html Initializes the Yuka.js `EntityManager` and `Time` objects. It then creates `GameEntity` instances for the main entity and the target, associating them with their respective Three.js meshes via a render component and a synchronization callback. The entity's maximum turn rate is also configured. ```JavaScript entityManager = new YUKA.EntityManager(); time = new YUKA.Time(); target = new YUKA.GameEntity(); target.setRenderComponent( targetMesh, sync ); entity = new YUKA.GameEntity(); entity.maxTurnRate = Math.PI * 0.5; entity.setRenderComponent( entityMesh, sync ); entityManager.add( entity ); entityManager.add( target ); ``` -------------------------------- ### Setting Up Three.js Scene and Lighting in JavaScript Source: https://github.com/mugen87/yuka/blob/master/examples/fuzzy/index.html This part of the `init` function configures the fundamental Three.js environment. It creates the scene, sets background color and fog, initializes the perspective camera, and adds a ground plane. Crucially, it sets up various light sources, including a directional light with shadow casting, and adds a polar grid helper for visual reference, preparing the 3D world for object placement. ```JavaScript function init() { scene = new THREE.Scene(); scene.background = new THREE.Color( 0xa0a0a0 ); scene.fog = new THREE.Fog( 0xa0a0a0, 20, 40 ); camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 200 ); camera.position.set( - 0.5, 2, - 2.5 ); camera.lookAt( 0, 0, 15 ); // const geometry = new THREE.PlaneBufferGeometry( 150, 150 ); const material = new THREE.MeshPhongMaterial( { color: 0x999999, depthWrite: false } ); const ground = new THREE.Mesh( geometry, material ); ground.rotation.x = - Math.PI / 2; ground.matrixAutoUpdate = false; ground.receiveShadow = true; ground.updateMatrix(); scene.add( ground ); // const hemiLight = new THREE.HemisphereLight( 0xffffff, 0x444444, 0.6 ); hemiLight.position.set( 0, 100, 0 ); hemiLight.matrixAutoUpdate = false; hemiLight.updateMatrix(); scene.add( hemiLight ); const dirLight = new THREE.DirectionalLight( 0xffffff, 0.8 ); dirLight.position.set( - 10, 10, 10 ); dirLight.matrixAutoUpdate = false; dirLight.updateMatrix(); dirLight.castShadow = true; dirLight.shadow.camera.top = 2; dirLight.shadow.camera.bottom = - 2; dirLight.shadow.camera.left = - 10; dirLight.shadow.camera.right = 10; dirLight.shadow.camera.near = 0.1; dirLight.shadow.camera.far = 20; dirLight.shadow.mapSize.x = 2048; dirLight.shadow.mapSize.y = 2048; dirLight.target.position.set( 0, 0, 10 ); scene.add( dirLight, dirLight.target ); // scene.add( new THREE.CameraHelper( dirLight.shadow.camera ) ); scene.add( new THREE.PolarGridHelper( 20, 20 ) ); ``` -------------------------------- ### Initializing World Module in JavaScript Source: https://github.com/mugen87/yuka/blob/master/examples/playground/shooter/index.html This JavaScript snippet imports the 'world' module from a local file and then calls its 'init' method. This is typically the entry point for setting up the game environment, loading assets, or configuring the simulation after the application starts. ```JavaScript import world from './src/World.js'; world.init(); ``` -------------------------------- ### Importing Libraries and Initializing Global State in JavaScript Source: https://github.com/mugen87/yuka/blob/master/examples/fuzzy/index.html This snippet imports necessary modules for 3D rendering (Three.js), game entity management and AI (Yuka.js), UI controls (dat.gui), and 3D model loading (GLTFLoader). It also declares global variables for scene components, game entities, and simulation parameters, then immediately calls the `init()` function to set up the application. ```JavaScript import * as YUKA from '../../build/yuka.module.js'; import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.109/build/three.module.js'; import * as DAT from 'https://cdn.jsdelivr.net/npm/dat.gui@0.7.7/build/dat.gui.module.js'; import { GLTFLoader } from 'https://cdn.jsdelivr.net/npm/three@0.109/examples/jsm/loaders/GLTFLoader.js'; import { Soldier } from './src/Soldier.js'; let camera, scene, renderer, mixers = []; let entityManager, time; let soldier, zombie, assaultRifle, shotgun; const params = { distance: 8, ammoShotgun: 12, ammoAssaultRifle: 30 }; init(); ``` -------------------------------- ### Initializing Blackjack Game Components and Event Listeners - JavaScript Source: https://github.com/mugen87/yuka/blob/master/examples/playground/blackjack/index.html This snippet defines global game state variables, imports necessary modules, and the `init` function. The `init` function sets up the game environment by creating a new shuffled deck, initializing player objects (dealer, AI, human), dealing initial cards, and attaching event listeners to UI buttons for 'stick', 'hit', and 'restart' actions. It ensures the game starts in a ready state and responds to user input. ```JavaScript import { ACTIONS } from './src/monteCarloSimulation/BlackjackEnvironment.js'; import Deck from './src/game/Deck.js'; import Player from './src/game/Player.js'; import AI from './src/game/AI.js'; const PLAYERS = Object.freeze( { HUMAN: 0, AI: 1, DEALER: 2 } ); let activePlayer = PLAYERS.HUMAN; let gameOver = false; let deck, dealer, ai, human; let humanWins = 0; let aiWins = 0; init(); function init() { deck = new Deck(); deck.shuffle(); dealer = new Player(); ai = new AI( dealer ); human = new Player(); dealCards(); const buttonStick = document.querySelector( '#button-stick' ); const buttonHit = document.querySelector( '#button-hit' ); const buttonRestart = document.querySelector( '#button-restart' ); buttonStick.addEventListener( 'pointerup', () => { activePlayer = PLAYERS.AI; updateGame(); } ); buttonHit.addEventListener( 'pointerup', () => { human.addCard( deck.nextCard() ); updateGame(); } ); buttonRestart.addEventListener( 'pointerup', () => { gameOver = false; activePlayer = PLAYERS.HUMAN; dealCards(); updateGame(); } ); updateGame(); } ``` -------------------------------- ### Initializing Game Scene and Logic (JavaScript) Source: https://github.com/mugen87/yuka/blob/master/examples/misc/savegame/index.html Sets up the Three.js scene, camera, and meshes for rendering. Initializes YUKA's EntityManager and Time, registers custom entity types, attaches event listeners for save/load/clear buttons, and either loads an existing savegame or initializes new entities. ```JavaScript function init() { scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 0.1, 1000 ); camera.position.set( 0, 0, 10 ); camera.lookAt( scene.position ); // const entityGeometry = new THREE.ConeBufferGeometry( 0.1, 0.5, 8 ); entityGeometry.rotateX( Math.PI * 0.5 ); const entityMaterial = new THREE.MeshNormalMaterial(); vehicleMesh = new THREE.Mesh( entityGeometry, entityMaterial ); vehicleMesh.matrixAutoUpdate = false; scene.add( vehicleMesh ); const targetGeometry = new THREE.SphereBufferGeometry( 0.05 ); const targetMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000 } ); targetMesh = new THREE.Mesh( targetGeometry, targetMaterial ); targetMesh.matrixAutoUpdate = false; scene.add( targetMesh ); // const sphereGeometry = new THREE.SphereBufferGeometry( 2, 32, 32 ); const sphereMaterial = new THREE.MeshBasicMaterial( { color: 0xcccccc, wireframe: true, transparent: true, opacity: 0.2 } ); const sphere = new THREE.Mesh( sphereGeometry, sphereMaterial ); scene.add( sphere ); // renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); // window.addEventListener( 'resize', onWindowResize, false ); const saveButton = document.getElementById( 'btn-save' ); saveButton.addEventListener( 'click', onSave, false ); const loadButton = document.getElementById( 'btn-load' ); loadButton.addEventListener( 'click', onLoad, false ); const clearButton = document.getElementById( 'btn-clear' ); clearButton.addEventListener( 'click', onClear, false ); // game setup entityManager = new YUKA.EntityManager(); time = new YUKA.Time(); // register custom types so the entity manager is able to instantiate // custom objects from JSON entityManager.registerType( 'CustomEntity', CustomEntity ); entityManager.registerType( 'CustomVehicle', CustomVehicle ); if ( hasSavegame() ) { // load an existing savegame onLoad(); } else { const target = new CustomEntity(); target.setRenderComponent( targetMesh, sync ); target.generatePosition(); const vehicle = new CustomVehicle(); vehicle.target = target; vehicle.setRenderComponent( vehicleMesh, sync ); const seekBehavior = new YUKA.SeekBehavior( target.position ); vehicle.steering.add( seekBehavior ); entityManager.add( target ); entityManager.add( vehicle ); } } ``` -------------------------------- ### Importing Libraries and Initializing Global Variables - JavaScript Source: https://github.com/mugen87/yuka/blob/master/examples/fsm/index.html This snippet imports necessary modules from Yuka and Three.js, including GLTFLoader for 3D model loading and a custom 'Girl' class. It also declares global variables for Three.js scene components (camera, scene, renderer, target) and Yuka's core components (entityManager, time), then immediately calls the 'init' function to set up the application. ```JavaScript import * as YUKA from '../../build/yuka.module.js'; import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.109/build/three.module.js'; import { GLTFLoader } from 'https://cdn.jsdelivr.net/npm/three@0.109/examples/jsm/loaders/GLTFLoader.js'; import { Girl } from './src/Girl.js'; let camera, scene, renderer, target = new THREE.Vector3(); let entityManager, time; init(); ``` -------------------------------- ### Importing YUKA and Three.js Modules (JavaScript) Source: https://github.com/mugen87/yuka/blob/master/examples/misc/savegame/index.html Imports necessary modules from YUKA for entity management and Three.js for 3D rendering, along with custom entity and vehicle classes, to set up the simulation environment. ```JavaScript import * as YUKA from '../../../build/yuka.module.js'; import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.109/build/three.module.js'; import { CustomEntity } from './src/CustomEntity.js'; import { CustomVehicle } from './src/CustomVehicle.js'; ``` -------------------------------- ### Importing Libraries and Initializing Global Variables - JavaScript Source: https://github.com/mugen87/yuka/blob/master/examples/steering/pursuit/index.html This snippet imports necessary modules from Yuka.js, Three.js, and dat.GUI, and declares global variables for the renderer, scene, camera, entity manager, time, and the pursuer, evader, and target entities. These variables are essential for setting up the 3D environment and game logic, and the `init()` and `animate()` functions are called to start the application. ```JavaScript import * as YUKA from '../../../build/yuka.module.js'; import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.109/build/three.module.js'; import * as DAT from 'https://cdn.jsdelivr.net/npm/dat.gui@0.7.7/build/dat.gui.module.js'; let renderer, scene, camera; let entityManager, time, pursuer, evader, target; init(); animate(); ``` -------------------------------- ### Creating Three.js Meshes for Game Objects Source: https://github.com/mugen87/yuka/blob/master/examples/math/orientation/index.html Defines and creates Three.js meshes for the main entity (a cone), the target (a small sphere), and a background sphere. These meshes are added to the scene and configured for manual matrix updates, which will be handled by Yuka.js. ```JavaScript const entityGeometry = new THREE.ConeBufferGeometry( 0.1, 0.5, 8 ); entityGeometry.rotateX( Math.PI * 0.5 ); const entityMaterial = new THREE.MeshNormalMaterial(); const entityMesh = new THREE.Mesh( entityGeometry, entityMaterial ); entityMesh.matrixAutoUpdate = false; scene.add( entityMesh ); const targetGeometry = new THREE.SphereBufferGeometry( 0.05 ); const targetMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000 } ); const targetMesh = new THREE.Mesh( targetGeometry, targetMaterial ); targetMesh.matrixAutoUpdate = false; scene.add( targetMesh ); const sphereGeometry = new THREE.SphereBufferGeometry( 2, 32, 32 ); const sphereMaterial = new THREE.MeshBasicMaterial( { color: 0xcccccc, wireframe: true, transparent: true, opacity: 0.2 } ); const sphere = new THREE.Mesh( sphereGeometry, sphereMaterial ); scene.add( sphere ); ``` -------------------------------- ### Importing Libraries and Initializing Globals in JavaScript Source: https://github.com/mugen87/yuka/blob/master/examples/goal/index.html Imports necessary modules from YUKA, Three.js, and custom local files (Girl, Collectible) to set up the game environment. Declares global variables for Three.js components (camera, scene, renderer) and YUKA components (entityManager, time), and calls the init() function to begin application setup. ```JavaScript import * as YUKA from '../../build/yuka.module.js'; import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.109/build/three.module.js'; import { GLTFLoader } from 'https://cdn.jsdelivr.net/npm/three@0.109/examples/jsm/loaders/GLTFLoader.js'; import { Girl } from './src/Girl.js'; import { Collectible } from './src/Collectible.js'; let camera, scene, renderer; let entityManager, time; init(); ``` -------------------------------- ### Initializing 3D Scene and Yuka Entities in JavaScript Source: https://github.com/mugen87/yuka/blob/master/examples/steering/followPath/index.html The `init` function sets up the Three.js scene, camera, and renderer. It also initializes Yuka's `EntityManager`, `Time`, and `Vehicle` objects. A `Path` is defined with multiple waypoints, and `FollowPathBehavior` and `OnPathBehavior` are added to the vehicle's steering capabilities to guide it along this path. Interactive controls are provided via dat.gui. ```JavaScript function init() { scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 0.1, 100 ); camera.position.set(0, 20, 0); camera.lookAt(scene.position); // const vehicleGeometry = new THREE.ConeBufferGeometry( 0.1, 0.5, 8 ); // vehicleGeometry.rotateX( Math.PI * 0.5 ); const vehicleMaterial = new THREE.MeshNormalMaterial(); const vehicleMesh = new THREE.Mesh(vehicleGeometry, vehicleMaterial); vehicleMesh.matrixAutoUpdate = false; scene.add(vehicleMesh); // dat.gui const gui = new DAT.GUI({ width: 300 }); gui.add(params, 'onPathActive').name('activate onPath').onChange((value) => onPathBehavior.active = value); gui.add(params, 'radius', 0.01, 1).name('radius').onChange((value) => onPathBehavior.radius = value); gui.open(); // renderer renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); // window.addEventListener( 'resize', onWindowResize, false ); // game setup entityManager = new YUKA.EntityManager(); time = new YUKA.Time(); vehicle = new YUKA.Vehicle(); vehicle.setRenderComponent(vehicleMesh, sync); const path = new YUKA.Path(); path.loop = true; path.add(new YUKA.Vector3(-4, 0, 4)); path.add(new YUKA.Vector3(-6, 0, 0)); path.add(new YUKA.Vector3(-4, 0, -4)); path.add(new YUKA.Vector3(0, 0, 0)); path.add(new YUKA.Vector3(4, 0, -4)); path.add(new YUKA.Vector3(6, 0, 0)); path.add(new YUKA.Vector3(4, 0, 4)); path.add(new YUKA.Vector3(0, 0, 6)); vehicle.position.copy(path.current()); // use "FollowPathBehavior" for basic path following const followPathBehavior = new YUKA.FollowPathBehavior(path, 0.5); vehicle.steering.add(followPathBehavior); // use "OnPathBehavior" to realize a more strict path following. // it's a separate steering behavior to provide more flexibility. onPathBehavior = new YUKA.OnPathBehavior(path); vehicle.steering.add(onPathBehavior); entityManager.add(vehicle); // const position = []; // for ( let i = 0; i < path._waypoints.length; i ++ ) { // const waypoint = path._waypoints[ i ]; // position.push( waypoint.x, waypoint.y, waypoint.z ); // } // const lineGeometry = new THREE.BufferGeometry(); // lineGeometry.addAttribute( 'position', new THREE.Float32BufferAttribute( position, 3 ) ); // const lineMaterial = new THREE.LineBasicMaterial( { color: 0xffffff } ); // const lines = new THREE.LineLoop( lineGeometry, lineMaterial ); // scene.add( lines ); } ``` -------------------------------- ### Running the Animation Loop (JavaScript) Source: https://github.com/mugen87/yuka/blob/master/examples/misc/savegame/index.html The main game loop that continuously updates the YUKA entity manager, calculates the delta time, and renders the Three.js scene, ensuring smooth animation and simulation progression. ```JavaScript function animate() { requestAnimationFrame( animate ); time.update(); const delta = time.getDelta(); entityManager.update( delta ); renderer.render( scene, camera ); } ``` -------------------------------- ### Styling Savegame Buttons (CSS) Source: https://github.com/mugen87/yuka/blob/master/examples/misc/savegame/index.html Defines basic CSS styles for interactive buttons, setting their dimensions, colors, background, and cursor properties to create a consistent look for save, load, and clear actions. ```CSS button { height: 20px; width: 100px; color: #ffffff; background: transparent; outline: 1px solid #ffffff; border: 0px; cursor: pointer; } ``` -------------------------------- ### Initializing Three.js Renderer and Yuka Core Components - JavaScript Source: https://github.com/mugen87/yuka/blob/master/examples/fsm/index.html This section of the 'init' function sets up the Three.js WebGLRenderer, configuring its pixel ratio, size, gamma output, and shadow mapping capabilities. It appends the renderer's DOM element to the document body and attaches a resize event listener. Crucially, it also initializes Yuka's EntityManager and Time instances, which are fundamental for managing and updating AI entities within the simulation. ```JavaScript renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.gammaOutput = true; renderer.shadowMap.enabled = true; document.body.appendChild( renderer.domElement ); window.addEventListener( 'resize', onWindowResize, false ); // game setup entityManager = new YUKA.EntityManager(); time = new YUKA.Time(); ``` -------------------------------- ### Handling Window Resize Event Source: https://github.com/mugen87/yuka/blob/master/examples/math/orientation/index.html Defines a function to respond to window resize events. It updates the camera's aspect ratio and projection matrix, and adjusts the renderer's size to match the new window dimensions, ensuring the scene remains correctly proportioned. ```JavaScript function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); } ``` -------------------------------- ### Initializing Three.js Scene and Yuka Game Entities Source: https://github.com/mugen87/yuka/blob/master/examples/steering/flee/index.html The `init` function sets up the Three.js scene, camera, renderer, and event listeners for window resizing and pointer movement. It also initializes Yuka's `EntityManager`, `Time`, and `Vehicle` objects, applying a `FleeBehavior` to the vehicle that targets a `YUKA.Vector3` controlled by user input. ```JavaScript function init() { scene = new THREE.Scene(); pointer = new THREE.Vector2( 1, 1 ); camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 0.1, 100 ); camera.position.set( 0, 10, 0 ); camera.lookAt( scene.position ); camera.updateMatrixWorld(); // const vehicleGeometry = new THREE.ConeBufferGeometry( 0.1, 0.5, 8 ); vehicleGeometry.rotateX( Math.PI * 0.5 ); const vehicleMaterial = new THREE.MeshNormalMaterial(); const vehicleMesh = new THREE.Mesh( vehicleGeometry, vehicleMaterial ); vehicleMesh.matrixAutoUpdate = false; scene.add( vehicleMesh ); const grid = new THREE.GridHelper( 10, 25 ); scene.add( grid ); // raycaster = new THREE.Raycaster(); plane = new THREE.Plane(); plane.normal.set( 0, 1, 0 ); renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); // document.addEventListener( 'mousemove', onPointerMove, false ); document.addEventListener( 'touchmove', onPointerMove, false ); document.addEventListener( 'touchstart', onPointerMove, false ); window.addEventListener( 'resize', onWindowResize, false ); // game setup target = new YUKA.Vector3(); entityManager = new YUKA.EntityManager(); time = new YUKA.Time(); vehicle = new YUKA.Vehicle(); vehicle.setRenderComponent( vehicleMesh, sync ); const fleeBehavior = new YUKA.FleeBehavior( target, 5 ); vehicle.steering.add( fleeBehavior ); entityManager.add( vehicle ); } ``` -------------------------------- ### Initializing Game World in JavaScript Source: https://github.com/mugen87/yuka/blob/master/examples/playground/hideAndSeek/index.html This JavaScript snippet imports the 'world' object from a local module and then calls its 'init()' method. This action is crucial for setting up and starting the game environment, likely handling scene creation, asset loading, and initial game state. ```JavaScript import world from './src/World.js'; world.init(); ``` -------------------------------- ### Generating Random Target Positions Source: https://github.com/mugen87/yuka/blob/master/examples/math/orientation/index.html Generates a new random position for the target entity on the surface of a sphere. It uses spherical coordinates to calculate the new position and schedules itself to run again after a 2-second delay, creating dynamic target movement. ```JavaScript function generateTarget() { // generate a random point on a sphere const radius = 2; const phi = Math.acos( ( 2 * Math.random() ) - 1 ); const theta = Math.random() * Math.PI * 2; target.position.fromSpherical( radius, phi, theta ); setTimeout( generateTarget, 2000 ); } ``` -------------------------------- ### Main Animation Loop Source: https://github.com/mugen87/yuka/blob/master/examples/math/orientation/index.html The core animation loop that continuously updates the scene. It calculates the time delta, instructs the main entity to rotate towards the target's position, updates the Yuka.js entity manager, and renders the Three.js scene. ```JavaScript function animate() { requestAnimationFrame( animate ); const delta = time.update().getDelta(); entity.rotateTo( target.position, delta ); entityManager.update(); renderer.render( scene, camera ); } ``` -------------------------------- ### Initializing Yuka and Three.js Environment Source: https://github.com/mugen87/yuka/blob/master/examples/steering/wander/index.html This snippet sets up the fundamental environment for a Yuka simulation integrated with Three.js. It imports necessary modules, declares global variables for rendering and simulation management, and calls the `init()` and `animate()` functions to start the application lifecycle. ```JavaScript import * as YUKA from '../../../build/yuka.module.js'; import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.109/build/three.module.js'; let renderer, scene, camera; let entityManager, time; init(); animate(); ``` -------------------------------- ### Loading GLTF Model and Configuring Animations - JavaScript Source: https://github.com/mugen87/yuka/blob/master/examples/fsm/index.html This code segment handles the loading of a 3D GLTF model ('yuka.glb') using Three.js's GLTFLoader. It configures the loaded avatar's materials for proper rendering (transparency, opacity, shadows) and sets up an AnimationMixer to control 'IDLE' and 'WALK' animations. Finally, it creates a 'Girl' entity with these animations and adds it to Yuka's entity manager for AI control. ```JavaScript const loadingManager = new THREE.LoadingManager( () => { const loadingScreen = document.getElementById( 'loading-screen' ); loadingScreen.classList.add( 'fade-out' ); loadingScreen.addEventListener( 'transitionend', onTransitionEnd ); animate(); } ); const glTFLoader = new GLTFLoader( loadingManager ); glTFLoader.load( 'model/yuka.glb', ( gltf ) => { // add object to scene const avatar = gltf.scene; avatar.animations = gltf.animations; avatar.traverse( ( object ) => { if ( object.isMesh ) { object.material.transparent = true; object.material.opacity = 1; object.material.alphaTest = 0.7; object.material.side = THREE.DoubleSide; object.castShadow = true; } } ); avatar.add( camera ); target.copy( avatar.position ); target.y += 1; camera.lookAt( target ); scene.add( avatar ); const mixer = new THREE.AnimationMixer( avatar ); const animations = new Map(); const idleAction = mixer.clipAction( 'Character_Idle' ); idleAction.play(); idleAction.enabled = false; const walkAction = mixer.clipAction( 'Character_Walk' ); walkAction.play(); walkAction.enabled = false; animations.set( 'IDLE', idleAction ); animations.set( 'WALK', walkAction ); const girl = new Girl( mixer, animations ); entityManager.add( girl ); } ); ``` -------------------------------- ### Initializing Three.js Scene and BVH Setup in JavaScript Source: https://github.com/mugen87/yuka/blob/master/examples/math/bvh/index.html This function sets up the Three.js scene, including camera, background, fog, ground plane, and lighting. It creates a torus knot mesh, configures the WebGL renderer, and adds OrbitControls for camera interaction. A dat.gui interface is initialized to allow users to adjust BVH parameters dynamically. Finally, it prepares the mesh geometry for YUKA's BVH and calls `createBVH()` to generate the initial BVH. ```JavaScript function init() { scene = new THREE.Scene(); scene.background = new THREE.Color( 0xa0a0a0 ); scene.fog = new THREE.Fog( 0xa0a0a0, 20, 40 ); camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 200 ); camera.position.set( 0, 3, - 8 ); // const geometry = new THREE.PlaneBufferGeometry( 150, 150 ); const material = new THREE.MeshPhongMaterial( { color: 0x999999, depthWrite: false } ); const ground = new THREE.Mesh( geometry, material ); ground.rotation.x = - Math.PI / 2; ground.matrixAutoUpdate = false; ground.receiveShadow = true; ground.updateMatrix(); scene.add( ground ); // const hemiLight = new THREE.HemisphereLight( 0xffffff, 0x444444, 0.6 ); hemiLight.position.set( 0, 100, 0 ); hemiLight.matrixAutoUpdate = false; hemiLight.updateMatrix(); scene.add( hemiLight ); const dirLight = new THREE.DirectionalLight( 0xffffff, 0.8 ); dirLight.position.set( - 4, 5, - 5 ); dirLight.matrixAutoUpdate = false; dirLight.updateMatrix(); dirLight.castShadow = true; dirLight.shadow.camera.top = 4; dirLight.shadow.camera.bottom = - 4; dirLight.shadow.camera.left = - 4; dirLight.shadow.camera.right = 4; dirLight.shadow.camera.near = 0.1; dirLight.shadow.camera.far = 20; scene.add( dirLight ); const sphereGeometry = new THREE.TorusKnotBufferGeometry( 1, 0.2, 64, 16 ).toNonIndexed(); const sphereMaterial = new THREE.MeshPhongMaterial( { color: 0xee0808 } ); const icoSphere = new THREE.Mesh( sphereGeometry, sphereMaterial ); icoSphere.position.set( 0, 1.5, 0 ); icoSphere.updateMatrix(); icoSphere.castShadow = true; scene.add( icoSphere ); // renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.gammaOutput = true; renderer.shadowMap.enabled = true; document.body.appendChild( renderer.domElement ); window.addEventListener( 'resize', onWindowResize, false ); const controls = new OrbitControls( camera, renderer.domElement ); controls.enableKeys = false; controls.enablePan = false; controls.target.copy( icoSphere.position ); controls.update(); // dat.gui const gui = new DAT.GUI( { width: 300 } ); gui.add( params, 'branchingFactor', 2, 6 ).step( 1 ).onChange( createBVH ); gui.add( params, 'primitivesPerNode', 1, 10 ).step( 1 ).onChange( createBVH ); gui.add( params, 'depth', 1, 8 ).step( 1 ).onChange( createBVH ); gui.add( params, 'meshVisible' ).onChange( ( value ) => icoSphere.visible = value ); gui.open(); // bvh setup const threeGeometry = sphereGeometry.clone(); threeGeometry.applyMatrix( icoSphere.matrix ); // transform vertices to world space const vertices = threeGeometry.attributes.position.array; meshGeometry = new YUKA.MeshGeometry( vertices ); createBVH(); } ``` -------------------------------- ### Importing Yuka and Three.js Modules and Declaring Global Variables Source: https://github.com/mugen87/yuka/blob/master/examples/steering/flee/index.html This snippet imports the necessary Yuka and Three.js modules from their respective paths. It also declares all global variables required for managing the Three.js scene (renderer, camera, scene), input handling (pointer, raycaster, plane), and Yuka game logic (entityManager, time, vehicle, target). ```JavaScript import * as YUKA from '../../../build/yuka.module.js'; import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.109/build/three.module.js'; let renderer, scene, camera; let pointer, raycaster, plane; let entityManager, time, vehicle, target; ``` -------------------------------- ### Handling Window Resize Event - JavaScript Source: https://github.com/mugen87/yuka/blob/master/examples/fsm/index.html This function is an event handler for window resize events. It dynamically adjusts the camera's aspect ratio and updates its projection matrix to prevent distortion. Additionally, it resizes the Three.js renderer to match the new window dimensions, ensuring the 3D scene remains properly scaled and displayed across different screen sizes. ```JavaScript function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); } ``` -------------------------------- ### Main Animation Loop - JavaScript Source: https://github.com/mugen87/yuka/blob/master/examples/fsm/index.html The 'animate' function defines the core rendering and simulation loop of the application. It uses 'requestAnimationFrame' for efficient browser rendering. Inside the loop, it calculates the time delta using Yuka's Time instance, updates all entities managed by Yuka's EntityManager, and finally renders the Three.js scene with the current camera view, ensuring continuous animation and AI updates. ```JavaScript function animate() { requestAnimationFrame( animate ); const delta = time.update().getDelta(); entityManager.update( delta ); renderer.render( scene, camera ); } ``` -------------------------------- ### Loading 3D Models with GLTFLoader in JavaScript Source: https://github.com/mugen87/yuka/blob/master/examples/fuzzy/index.html This section of the `init` function is responsible for asynchronously loading 3D models (soldier, zombie, shotgun, assault rifle) using Three.js's `GLTFLoader`. For each loaded model, it configures rendering properties like shadow casting and material side, and sets initial scale, rotation, and position. The soldier and zombie models are also integrated with Yuka.js entities and their animations are prepared. ```JavaScript ``` -------------------------------- ### Declaring Global Scene Variables (JavaScript) Source: https://github.com/mugen87/yuka/blob/master/examples/misc/savegame/index.html Declares global variables for Three.js (renderer, scene, camera, meshes) and YUKA (entityManager, time) to be accessible across different functions, facilitating the setup and update of the 3D environment and game logic. ```JavaScript let renderer, scene, camera; let entityManager, time; let targetMesh, vehicleMesh; ``` -------------------------------- ### Setting Up 3D Scene and Graph Initialization - JavaScript Source: https://github.com/mugen87/yuka/blob/master/examples/graph/basic/index.html The init function sets up the Three.js environment, including the scene, perspective camera, WebGL renderer, and raycaster for interaction. It creates a grid-based YUKA graph, adds visual helpers for the graph, and initializes the dat.gui panel for selecting search algorithms. It also attaches event listeners for mouse interaction. ```JavaScript function init() { scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 0.1, 1000 ); camera.position.set( 50, 50, 0 ); camera.lookAt( scene.position ); raycaster = new THREE.Raycaster(); // renderer renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); // window.addEventListener( 'resize', onWindowResize, false ); document.addEventListener( 'mousedown', onDocumentMouseDown, false ); // graph graph = YUKA.GraphUtils.createGridLayout( 50, 10 ); const graphHelper = createGraphHelper( graph, 0.25 ); scene.add( graphHelper ); graphHelper.traverse( ( child ) => { if ( child.isMesh ) nodes.push( child ); } ); performSearch(); // dat.gui const gui = new DAT.GUI( { width: 300 } ); gui.add( params, 'algorithm', [ 'AStar', 'Dijkstra', 'BFS', 'DFS' ] ).onChange( performSearch ); gui.open(); } ``` -------------------------------- ### Checking for Existing Savegame (JavaScript) Source: https://github.com/mugen87/yuka/blob/master/examples/misc/savegame/index.html Determines if a savegame currently exists in local storage by checking for the presence of the 'yuka_savegame' item. ```JavaScript function hasSavegame() { return localStorage.getItem( 'yuka_savegame' ) !== null; } ``` -------------------------------- ### Clearing Savegame from Local Storage (JavaScript) Source: https://github.com/mugen87/yuka/blob/master/examples/misc/savegame/index.html Removes the stored savegame data from local storage, effectively deleting the persisted game state. ```JavaScript function onClear() { localStorage.removeItem( 'yuka_savegame' ); } ``` -------------------------------- ### Setting Up Three.js WebGLRenderer and UI Interactions Source: https://github.com/mugen87/yuka/blob/master/examples/navigation/firstperson/index.html This section initializes the WebGLRenderer with antialiasing, sets its size to match the window, and appends its DOM element to the document body. It also registers a resize event listener for the window and a click listener for an 'intro' element to connect controls and resume the audio context. ```JavaScript renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.gammaOutput = true; document.body.appendChild( renderer.domElement ); window.addEventListener( 'resize', onWindowResize, false ); const intro = document.getElementById( 'intro' ); intro.addEventListener( 'click', () => { controls.connect(); const context = THREE.AudioContext.getContext(); if ( context.state === 'suspended' ) context.resume(); }, false ); ``` -------------------------------- ### Handling Window Resize Event (JavaScript) Source: https://github.com/mugen87/yuka/blob/master/examples/misc/savegame/index.html Adjusts the camera's aspect ratio and the renderer's size when the browser window is resized, ensuring the 3D scene scales correctly and maintains its visual integrity. ```JavaScript function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); } ``` -------------------------------- ### Saving Game State to Local Storage (JavaScript) Source: https://github.com/mugen87/yuka/blob/master/examples/misc/savegame/index.html Serializes the current state of the YUKA entity manager into a JSON string and stores it in the browser's local storage, allowing the game state to be persisted across sessions. ```JavaScript function onSave() { const json = entityManager.toJSON(); const jsonString = JSON.stringify( json ); localStorage.setItem( 'yuka_savegame', jsonString ); } ```