### Basic Touch Joystick Setup Example Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/input/TouchJoystickHandler.md Example demonstrating how to set up and use the TouchJoystickHandler within a TypeScript script component. ```APIDOC ## Usage Examples ### Basic Touch Joystick Setup ```typescript class MobileController extends TOOLKIT.ScriptComponent { public joystick: TOOLKIT.TouchJoystickHandler; public moveSpeed: number = 5.0; protected start(): void { this.setupTouchJoystick(); } private setupTouchJoystick(): void { this.joystick = new TOOLKIT.TouchJoystickHandler( "joystick-stick", 100, 20, true, TOOLKIT.TouchMouseButton.Left, "joystick-base" ); this.joystick.enabled = true; this.joystick.updateElements = true; this.joystick.preventDefault = true; this.joystick.stopPropagation = true; this.joystick.baseElementOpacity = "0.5"; this.joystick.stickElementOpacity = "0.8"; this.setupJoystickEvents(); } private setupJoystickEvents(): void { this.joystick.onHandleDown = (event) => { console.log("Joystick activated"); }; this.joystick.onHandleMove = (event) => { this.handleMovement(); }; this.joystick.onHandleUp = (event) => { console.log("Joystick released"); }; } protected update(): void { if (this.joystick.isActive()) { this.handleMovement(); } } private handleMovement(): void { const inputX = this.joystick.getInputX(); const inputY = this.joystick.getInputY(); const magnitude = this.joystick.getInputMagnitude(); if (magnitude > 0.1) { const deltaTime = TOOLKIT.SceneManager.GetDeltaTime(); const moveVector = new BABYLON.Vector3(inputX, 0, inputY); moveVector.scaleInPlace(this.moveSpeed * magnitude * deltaTime); this.transform.position.addInPlace(moveVector); } } protected destroy(): void { if (this.joystick) { this.joystick.dispose(); } } } ``` ``` -------------------------------- ### Usage Examples Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/physics/SimpleCharacterController.md Examples demonstrating how to use the SimpleCharacterController for basic setup, movement, rotation, and direct position control. ```APIDOC ## Usage Examples ### Basic Character Setup ```typescript const simpleController = new TOOLKIT.SimpleCharacterController(transform, scene); ``` ### Character Movement ```typescript const moveSpeed = 5.0; const deltaTime = scene.getEngine().getDeltaTime() / 1000.0; const inputDirection = new BABYLON.Vector3(); if (TOOLKIT.InputController.GetKeyboardInput(87)) { // W key inputDirection.z = 1.0; } if (TOOLKIT.InputController.GetKeyboardInput(83)) { // S key inputDirection.z = -1.0; } if (TOOLKIT.InputController.GetKeyboardInput(65)) { // A key inputDirection.x = -1.0; } if (TOOLKIT.InputController.GetKeyboardInput(68)) { // D key inputDirection.x = 1.0; } inputDirection.normalize(); inputDirection.scaleInPlace(moveSpeed * deltaTime); simpleController.move(inputDirection); ``` ### Character Rotation ```typescript const mouseSensitivity = 0.002; const mouseX = TOOLKIT.InputController.GetUserInput(TOOLKIT.UserInputAxis.MouseX); const mouseY = TOOLKIT.InputController.GetUserInput(TOOLKIT.UserInputAxis.MouseY); const yawAngle = mouseX * mouseSensitivity; const pitchAngle = mouseY * mouseSensitivity; simpleController.turn(yawAngle); const rotation = BABYLON.Quaternion.RotationYawPitchRoll(yawAngle, pitchAngle, 0); simpleController.rotate(rotation.x, rotation.y, rotation.z, rotation.w); ``` ### Direct Position Control ```typescript simpleController.set(10, 0, 5); const targetRotation = BABYLON.Quaternion.RotationY(Math.PI / 2); simpleController.set( 10, 0, 5, targetRotation.x, targetRotation.y, targetRotation.z, targetRotation.w ); ``` ``` -------------------------------- ### Basic WebVideoPlayer Setup Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/video/WebVideoPlayer.md Initializes and configures a WebVideoPlayer instance with basic playback properties. Ensure the component is awake and started after configuration. ```typescript const videoPlayer = new TOOLKIT.WebVideoPlayer(transform, scene); videoPlayer.videoName = "introVideo"; videoPlayer.videoUrl = "./videos/intro.mp4"; videoPlayer.videoAutoPlay = true; videoPlayer.videoLoop = false; videoPlayer.videoVolume = 0.8; videoPlayer.awake(); videoPlayer.start(); ``` -------------------------------- ### Basic Audio Playback Setup Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/audio/AudioSource.md Demonstrates how to initialize an AudioSource component, load an audio clip, configure basic playback settings like volume and looping, and start playback. ```typescript const audioSource = new TOOLKIT.AudioSource(transform, scene); const sound = new BABYLON.Sound("music", "./audio/background.wav", scene); audioSource.setAudioClip(sound); audioSource.setVolume(0.8); audioSource.setLoop(true); audioSource.playOnAwake = true; audioSource.play(); ``` -------------------------------- ### Basic Input Configuration Example Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/input/UserInputOptions.md Example demonstrating how to apply basic input configurations for keyboard, gamepad, and mouse. ```APIDOC ## Basic Input Configuration ### Description Example demonstrating how to apply basic input configurations for keyboard, gamepad, and mouse. ### Code Example ```typescript class InputConfigurationManager extends TOOLKIT.ScriptComponent { protected start(): void { this.setupBasicInputConfiguration(); } private setupBasicInputConfiguration(): void { TOOLKIT.UserInputOptions.KeyboardSmoothing = true; TOOLKIT.UserInputOptions.KeyboardMoveSensibility = 2.0; TOOLKIT.UserInputOptions.KeyboardArrowSensibility = 1.5; TOOLKIT.UserInputOptions.KeyboardMoveDeadZone = 0.1; TOOLKIT.UserInputOptions.GamepadDeadStickValue = 0.15; TOOLKIT.UserInputOptions.GamepadLStickSensibility = 1.0; TOOLKIT.UserInputOptions.GamepadRStickSensibility = 1.2; TOOLKIT.UserInputOptions.PointerMouseDeadZone = 0.05; TOOLKIT.UserInputOptions.PointerWheelDeadZone = 0.1; console.log("Basic input configuration applied"); } protected update(): void { this.logCurrentConfiguration(); } private logCurrentConfiguration(): void { console.log(`Keyboard Sensitivity: ${TOOLKIT.UserInputOptions.KeyboardMoveSensibility}`); console.log(`Gamepad Dead Zone: ${TOOLKIT.UserInputOptions.GamepadDeadStickValue}`); console.log(`Mouse Dead Zone: ${TOOLKIT.UserInputOptions.PointerMouseDeadZone}`); } } ``` ``` -------------------------------- ### Basic Vehicle Creation Example Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/physics/HavokRaycastVehicle.md Example demonstrating how to create and initialize a HavokRaycastVehicle. ```APIDOC ## Basic Vehicle Creation ### Description Example demonstrating how to create and initialize a HavokRaycastVehicle. ### Code ```typescript const vehicleOptions = { chassisBody: chassisPhysicsBody, indexRightAxis: 0, indexUpAxis: 1, indexForwardAxis: 2 }; const havokVehicle = new TOOLKIT.HavokRaycastVehicle(vehicleOptions); havokVehicle.addToWorld(scene.getPhysicsEngine()); ``` ``` -------------------------------- ### Basic Blend Tree Value Creation Example Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/animation/BlendTreeValue.md Demonstrates how to create and manage multiple BlendTreeValue instances within a script component for animation setup. ```APIDOC ## Usage Examples ### Basic Blend Tree Value Creation ```typescript class BlendTreeSetup extends TOOLKIT.ScriptComponent { public blendValues: TOOLKIT.BlendTreeValue[] = []; protected start(): void { this.createBlendTreeValues(); } private createBlendTreeValues(): void { const idleValue = new TOOLKIT.BlendTreeValue({ source: { motion: "idle" }, motion: "idle", posX: 0.0, posY: 0.0, weight: 1.0 }); const walkValue = new TOOLKIT.BlendTreeValue({ source: { motion: "walk" }, motion: "walk", posX: 5.0, posY: 0.0, weight: 0.0 }); const runValue = new TOOLKIT.BlendTreeValue({ source: { motion: "run" }, motion: "run", posX: 10.0, posY: 0.0, weight: 0.0 }); this.blendValues = [idleValue, walkValue, runValue]; } protected update(): void { this.displayBlendWeights(); } private displayBlendWeights(): void { for (const value of this.blendValues) { if (value.weight > 0.01) { console.log(`${value.motion}: weight=${value.weight.toFixed(3)} pos=(${value.posX}, ${value.posY})`); } } } } ``` ``` -------------------------------- ### Install Babylon Toolkit via npm (UMD) Source: https://github.com/babylonjs/babylontoolkit/blob/master/readme.md Install the UMD version of the Babylon Toolkit using npm. ```bash npm install babylonjs-toolkit ``` -------------------------------- ### Transform Utilities Examples Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/core/Utilities.md Shows how to retrieve world space positions, transform points, and get direction vectors from a transform. ```typescript // Get world space position const worldPos = TOOLKIT.Utilities.GetAbsolutePosition(transform); // Transform point to world space const worldPoint = TOOLKIT.Utilities.TransformPoint(transform, localPoint); // Get direction vectors const forward = TOOLKIT.Utilities.GetForwardVector(transform); const right = TOOLKIT.Utilities.GetRightVector(transform); ``` -------------------------------- ### Install Babylon Toolkit via npm (ES6) Source: https://github.com/babylonjs/babylontoolkit/blob/master/readme.md Install the ES6 version of the Babylon Toolkit using npm. ```bash npm install @babylonjs-toolkit/next ``` -------------------------------- ### BlendTreeManager Class Example Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/animation/BlendTreeSystem.md Demonstrates the setup and update logic for managing locomotion and combat blend trees within a script component. It handles switching between blend modes and calculating blend weights. ```typescript class BlendTreeManager extends TOOLKIT.ScriptComponent { public locomotionBlendTree: TOOLKIT.BlendTreeValue[] = []; public combatBlendTree: TOOLKIT.BlendTreeValue[] = []; public currentBlendTree: TOOLKIT.BlendTreeValue[] = []; public blendMode: string = "locomotion"; protected start(): void { this.setupAllBlendTrees(); } private setupAllBlendTrees(): void { this.setupLocomotionBlendTree(); this.setupCombatBlendTree(); this.currentBlendTree = this.locomotionBlendTree; } private setupLocomotionBlendTree(): void { this.locomotionBlendTree = [ new TOOLKIT.BlendTreeValue({ source: { motion: "idle" }, motion: "idle", posX: 0.0, posY: 0.0, weight: 0.0 }), new TOOLKIT.BlendTreeValue({ source: { motion: "walk" }, motion: "walk", posX: 0.0, posY: 5.0, weight: 0.0 }), new TOOLKIT.BlendTreeValue({ source: { motion: "run" }, motion: "run", posX: 0.0, posY: 10.0, weight: 0.0 }) ]; } private setupCombatBlendTree(): void { this.combatBlendTree = [ new TOOLKIT.BlendTreeValue({ source: { motion: "combatIdle" }, motion: "combatIdle", posX: 0.0, posY: 0.0, weight: 0.0 }), new TOOLKIT.BlendTreeValue({ source: { motion: "combatWalk" }, motion: "combatWalk", posX: 0.0, posY: 3.0, weight: 0.0 }) ]; } protected update(): void { this.updateBlendTreeCalculations(); } private updateBlendTreeCalculations(): void { const input = this.getBlendInput(); switch (this.blendMode) { case "locomotion": this.calculateLocomotionBlending(input); break; case "combat": this.calculateCombatBlending(input); break; } } private getBlendInput(): { x: number, y: number } { return { x: 0.0, y: 6.5 }; } private calculateLocomotionBlending(input: { x: number, y: number }): void { TOOLKIT.BlendTreeSystem.Calculate2DFreeformDirectional( input.x, input.y, this.locomotionBlendTree ); } private calculateCombatBlending(input: { x: number, y: number }): void { TOOLKIT.BlendTreeSystem.Calculate1DSimpleBlendTree( input.y, this.combatBlendTree ); } public switchBlendMode(mode: string): void { this.blendMode = mode; this.currentBlendTree = mode === "combat" ? this.combatBlendTree : this.locomotionBlendTree; } } ``` -------------------------------- ### State Machine Setup Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/animation/AnimationState.md Illustrates how to enable the state machine, add animation states with associated animations and properties, and set the default state. ```typescript // Enable state machine animState.enableStateMachine = true; // Add states animState.addState("idle", "idle_animation", true, 1.0); animState.addState("walk", "walk_animation", true, 1.0); animState.addState("run", "run_animation", true, 1.5); animState.addState("jump", "jump_animation", false, 1.0); // Set default state animState.defaultStateName = "idle"; animState.setState("idle"); ``` -------------------------------- ### Basic Animation Mixing Example Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/animation/AnimationMixer.md Demonstrates how to set up and update animation blending using AnimationMixer properties. ```APIDOC ## Basic Animation Mixing ```typescript class CharacterAnimator extends TOOLKIT.ScriptComponent { public walkAnimation: string = "walk"; public runAnimation: string = "run"; public mixer: TOOLKIT.AnimationMixer = {} as TOOLKIT.AnimationMixer; protected start(): void { this.setupAnimationMixer(); } private setupAnimationMixer(): void { this.mixer.blendingFactor = 0.5; this.mixer.blendingSpeed = 2.0; this.mixer.influenceBuffer = 1.0; } protected update(): void { this.updateAnimationBlending(); } private updateAnimationBlending(): void { const speed = this.getMovementSpeed(); if (speed > 5.0) { this.mixer.blendingFactor = Math.min(1.0, speed / 10.0); } else { this.mixer.blendingFactor = Math.max(0.0, speed / 5.0); } } private getMovementSpeed(): number { return 7.5; } } ``` ``` -------------------------------- ### Loading Unity Audio Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/interfaces/Unity.md Example demonstrating how to load Unity audio clip data into a Babylon.js Sound object. ```APIDOC ## Loading Unity Audio ### Description Loads Unity audio clip data into a Babylon.js Sound object, with options for looping, autoplay, and volume. ### Usage ```typescript // Load Unity audio clip async function loadUnityAudio(data: TOOLKIT.IUnityAudioClip, scene: BABYLON.Scene): Promise { const sound = await TOOLKIT.Utilities.ParseSound( data, scene, data.name, () => console.log(`Audio ${data.name} loaded`), { loop: false, autoplay: false, volume: 1.0 } ); return sound; } ``` ``` -------------------------------- ### Advanced Joystick System Example Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/input/TouchJoystickHandler.md Illustrates a complete implementation of an advanced joystick system using the TouchJoystickHandler, including input smoothing and application. ```APIDOC ## AdvancedJoystickSystem ### Description Manages an advanced touch joystick, handling its configuration, input events, and applying smoothed input for character movement. ### Properties - **joystick** (TouchJoystickHandler) - The instance of the TouchJoystickHandler. - **sensitivity** (number) - Controls the sensitivity of the joystick input. - **smoothing** (number) - Controls the smoothing factor for input values. - **currentInput** (BABYLON.Vector2) - The smoothed current input vector. - **targetInput** (BABYLON.Vector2) - The raw, unsmoothed target input vector. ### Methods - **start()**: Initializes the joystick system. - **setupAdvancedJoystick()**: Creates and configures the TouchJoystickHandler instance. - **configureAdvancedSettings()**: Sets various configuration properties for the joystick. - **setupAdvancedEvents()**: Assigns callback functions to joystick events (onHandleDown, onHandleMove, onHandleUp). - **onJoystickActivated(event)**: Handles logic when the joystick is activated. - **onJoystickMoved(event)**: Processes joystick movement, applying sensitivity and curve. - **onJoystickReleased(event)**: Resets input and visual states when the joystick is released. - **update()**: Called every frame to update smoothed input and apply movement. - **updateSmoothInput()**: Applies smoothing to the current input vector. - **applyInput()**: Moves the associated transform based on the smoothed input. - **setJoystickSensitivity(sensitivity: number)**: Public method to set the joystick sensitivity within a defined range. - **setJoystickSmoothing(smoothing: number)**: Public method to set the joystick smoothing factor within a defined range. - **getJoystickInfo()**: Returns an object containing current joystick status and input information. - **destroy()**: Disposes of the joystick handler when the system is destroyed. ``` -------------------------------- ### Physics Engine Setup Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/physics/RigidbodyPhysics.md Methods for configuring and setting up the physics engine and components within a Babylon.js scene. ```APIDOC ## ConfigurePhysicsEngine(scene, deltaWorldStep?, subTimeStep?, maxWorldSweep?, ccdEnabled?, ccdPenetration?, gravityLevel?) ### Description Configure the physics engine with advanced settings. ### Parameters - `scene` `BABYLON.Scene` - The scene instance - `deltaWorldStep?` `boolean` - Use delta world stepping - `subTimeStep?` `number` - Sub-timestep value - `maxWorldSweep?` `number` - Maximum world sweep distance - `ccdEnabled?` `boolean` - Enable continuous collision detection - `ccdPenetration?` `number` - CCD penetration threshold - `gravityLevel?` `BABYLON.Vector3` - Gravity vector ### Returns `Promise` - Configuration completion promise ``` ```APIDOC ## SetupPhysicsComponent(scene, entity) ### Description Set up physics component for a transform node. ### Parameters - `scene` `BABYLON.Scene` - The scene instance - `entity` `BABYLON.TransformNode` - The transform node to add physics to ``` -------------------------------- ### Advanced Root Motion Handling Example Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/animation/AnimationMixer.md Illustrates how to initialize and apply root motion using AnimationMixer's root position and rotation properties. ```APIDOC ## Advanced Root Motion Handling ```typescript class RootMotionController extends TOOLKIT.ScriptComponent { public mixer: TOOLKIT.AnimationMixer = {} as TOOLKIT.AnimationMixer; public enableRootMotion: boolean = true; protected start(): void { this.initializeRootMotion(); } private initializeRootMotion(): void { this.mixer.rootPosition = BABYLON.Vector3.Zero(); this.mixer.rootRotation = BABYLON.Quaternion.Identity(); } protected update(): void { if (this.enableRootMotion) { this.applyRootMotion(); } } private applyRootMotion(): void { const deltaTime = TOOLKIT.SceneManager.GetDeltaTime(); const rootMotionPosition = this.mixer.rootPosition.scale(deltaTime); const rootMotionRotation = this.mixer.rootRotation; this.transform.position.addInPlace(rootMotionPosition); this.transform.rotationQuaternion = this.transform.rotationQuaternion.multiply(rootMotionRotation); } } ``` ``` -------------------------------- ### Converting Unity Vectors and Colors Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/interfaces/Unity.md Examples showing how to convert Unity vector and color data structures to their Babylon.js equivalents. ```APIDOC ## Converting Unity Vectors ### Description Converts Unity Vector3 data structure to a Babylon.js Vector3. ### Usage ```typescript // Convert Unity Vector3 to Babylon Vector3 function convertVector3(unityVec: TOOLKIT.IUnityVector3): BABYLON.Vector3 { return TOOLKIT.Utilities.ParseVector3(unityVec, BABYLON.Vector3.Zero()); } ``` ## Converting Unity Colors ### Description Converts Unity Color data structure to Babylon.js Color3 and Color4. ### Usage ```typescript // Convert Unity Color to Babylon Color3 function convertColor3(unityColor: TOOLKIT.IUnityColor): BABYLON.Color3 { return TOOLKIT.Utilities.ParseColor3(unityColor, BABYLON.Color3.White(), true); } // Convert Unity Color to Babylon Color4 function convertColor4(unityColor: TOOLKIT.IUnityColor): BABYLON.Color4 { return TOOLKIT.Utilities.ParseColor4(unityColor, BABYLON.Color4.FromColor3(BABYLON.Color3.White()), true); } ``` ``` -------------------------------- ### Parsing Unity Assets Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/interfaces/Unity.md Examples demonstrating how to parse Unity transform and texture data into Babylon.js objects. ```APIDOC ## Parsing Unity Transform ### Description Parses Unity transform data into a Babylon.js TransformNode, setting layer and tag information. ### Usage ```typescript // Parse Unity transform data function parseUnityTransform(data: TOOLKIT.IUnityTransform, scene: BABYLON.Scene): BABYLON.TransformNode { const transform = TOOLKIT.Utilities.ParseTransformByID(data, scene); // Set layer and tag information TOOLKIT.SceneManager.SetTransformLayer(transform, data.layer); TOOLKIT.SceneManager.SetTransformTag(transform, data.tag); return transform; } ``` ## Parsing Unity Texture ### Description Parses Unity texture data into a Babylon.js Texture, configuring mipmap, Y inversion, filtering, and wrap modes. ### Usage ```typescript // Parse Unity texture function parseUnityTexture(data: TOOLKIT.IUnityTexture, scene: BABYLON.Scene): BABYLON.Texture { const texture = TOOLKIT.Utilities.ParseTexture( data, scene, !data.mipmap, // noMipmap false, // invertY data.filtermode === "Point" ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.TRILINEAR_SAMPLINGMODE ); // Set wrap mode if (data.wrapmode === "Repeat") { texture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE; texture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE; } else if (data.wrapmode === "Clamp") { texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; } return texture; } ``` ``` -------------------------------- ### Basic Raycast Hit Detection Example Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/utilities/RaycastHitResult.md Demonstrates how to use the RaycastHitResult class to perform a raycast and process the results. ```APIDOC ## Usage Examples ### Basic Raycast Hit Detection ```typescript class RaycastHitDetection extends TOOLKIT.ScriptComponent { protected update(): void { this.performRaycast(); } private performRaycast(): void { const origin = this.transform.position; const direction = this.transform.forward; const ray = new BABYLON.Ray(origin, direction); const hitResult = this.castRay(ray); if (hitResult.hit) { this.processHit(hitResult); } } private castRay(ray: BABYLON.Ray): TOOLKIT.RaycastHitResult { const hitResult = new TOOLKIT.RaycastHitResult(); const pickInfo = this.scene.pickWithRay(ray); if (pickInfo && pickInfo.hit) { hitResult.hit = true; hitResult.distance = pickInfo.distance; hitResult.point = pickInfo.pickedPoint; hitResult.normal = pickInfo.getNormal(); hitResult.pickedMesh = pickInfo.pickedMesh; hitResult.faceId = pickInfo.faceId; hitResult.ray = ray; } else { hitResult.hit = false; } return hitResult; } private processHit(hitResult: TOOLKIT.RaycastHitResult): void { console.log(`Hit detected at distance: ${hitResult.distance}`); console.log(`Hit point: ${hitResult.point}`); console.log(`Hit mesh: ${hitResult.pickedMesh.name}`); } } ``` ``` -------------------------------- ### Rotation Operations Examples Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/core/Utilities.md Illustrates quaternion to Euler angle conversion, creating look rotations, and rotating vectors. ```typescript // Convert quaternion to Euler angles const euler = TOOLKIT.Utilities.ToEuler(transform.rotationQuaternion); // Create look rotation const lookRot = TOOLKIT.Utilities.LookRotation(targetDirection); // Rotate vector const rotatedVec = TOOLKIT.Utilities.RotateVector(localVector, rotation); ``` -------------------------------- ### Implement Physics Body Component Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/interfaces/Physics.md Example implementation of a physics body component, extending ScriptComponent and implementing IPhysicsBody. It includes default values and a basic setup method. ```typescript class PhysicsBodyComponent extends TOOLKIT.ScriptComponent implements TOOLKIT.IPhysicsBody { public mass: number = 1.0; public isKinematic: boolean = false; public useGravity: boolean = true; public linearDamping: number = 0.0; public angularDamping: number = 0.05; public freezePosition: boolean[] = [false, false, false]; public freezeRotation: boolean[] = [false, false, false]; protected start(): void { this.setupPhysicsBody(); } private setupPhysicsBody(): void { console.log(`Physics body configured with mass: ${this.mass}`); } } ``` -------------------------------- ### Basic Trigger Volume Setup Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/utilities/TriggerVolume.md Demonstrates how to initialize a trigger volume, define its shape and size, set up event callbacks for object entry, stay, and exit, and configure detection filters. This is useful for creating interactive zones in a scene. ```typescript class BasicTriggerSystem extends TOOLKIT.ScriptComponent { public triggerVolume: TOOLKIT.TriggerVolume; protected start(): void { this.setupTriggerVolume(); } private setupTriggerVolume(): void { this.triggerVolume = new TOOLKIT.TriggerVolume(); this.triggerVolume.createTriggerVolume( "box", new BABYLON.Vector3(5, 3, 5), new BABYLON.Vector3(0, 1.5, 0) ); this.triggerVolume.setTriggerCallbacks( (other) => this.onObjectEnter(other), (other) => this.onObjectStay(other), (other) => this.onObjectExit(other) ); this.triggerVolume.setDetectionFilters(true, true, false); this.triggerVolume.enableTrigger(true); console.log("Basic trigger volume setup complete"); } private onObjectEnter(other: BABYLON.AbstractMesh): void { console.log(`Object entered trigger: ${other.name}`); } private onObjectStay(other: BABYLON.AbstractMesh): void { console.log(`Object staying in trigger: ${other.name}`); } private onObjectExit(other: BABYLON.AbstractMesh): void { console.log(`Object exited trigger: ${other.name}`); } } ``` -------------------------------- ### Basic Navigation Setup Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/navigation/NavigationAgent.md Initializes and configures the navigation agent component. Sets properties like angular speed, stopping distance, and height offset. Also demonstrates how to set up event handlers for agent readiness and navigation completion. ```typescript const agent = TOOLKIT.SceneManager.GetComponent(enemyTransform, "TOOLKIT.NavigationAgent"); agent.angularSpeed = 180; // degrees per second agent.stoppingDistance = 1.0; agent.heightOffset = 0.1; agent.onReadyObservable.add(() => { console.log("Navigation agent is ready"); }); agent.onNavCompleteObservable.add(() => { console.log("Navigation complete"); }); ``` -------------------------------- ### Basic Asset Preloading Example Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/assets/PreloadAssetsManager.md Demonstrates how to use the PreloadAssetsManager to preload textures, meshes, and audio files. It includes progress updates and caching of loaded assets. ```typescript class AssetPreloader extends TOOLKIT.ScriptComponent { public loadingProgress: number = 0; public assetsLoaded: boolean = false; protected start(): void { this.preloadGameAssets(); } private preloadGameAssets(): void { const textureUrls = [ "./textures/player.jpg", "./textures/environment.jpg", "./textures/ui_elements.png" ]; const meshUrls = [ "./models/player.babylon", "./models/environment.babylon", "./models/weapons.babylon" ]; const audioUrls = [ "./audio/background_music.mp3", "./audio/sound_effects.wav", "./audio/voice_lines.ogg" ]; this.preloadTextures(textureUrls); this.preloadMeshes(meshUrls); this.preloadAudio(audioUrls); } private preloadTextures(urls: string[]): void { TOOLKIT.PreloadAssetsManager.PreloadTextures( urls, (loaded, total) => { console.log(`Textures: ${loaded}/${total} loaded`); this.updateProgress("textures", loaded / total); }, (textures) => { console.log(`All ${textures.length} textures loaded successfully`); this.onTexturesLoaded(textures); } ); } private preloadMeshes(urls: string[]): void { TOOLKIT.PreloadAssetsManager.PreloadMeshes( urls, (loaded, total) => { console.log(`Meshes: ${loaded}/${total} loaded`); this.updateProgress("meshes", loaded / total); }, (meshes) => { console.log(`All ${meshes.length} meshes loaded successfully`); this.onMeshesLoaded(meshes); } ); } private preloadAudio(urls: string[]): void { TOOLKIT.PreloadAssetsManager.PreloadAudio( urls, (loaded, total) => { console.log(`Audio: ${loaded}/${total} loaded`); this.updateProgress("audio", loaded / total); }, (sounds) => { console.log(`All ${sounds.length} audio files loaded successfully`); this.onAudioLoaded(sounds); } ); } private updateProgress(category: string, progress: number): void { this.loadingProgress = progress * 100; console.log(`${category} loading progress: ${this.loadingProgress.toFixed(1)}%`); } private onTexturesLoaded(textures: any[]): void { textures.forEach((texture, index) => { TOOLKIT.PreloadAssetsManager.CacheAsset(`texture_${index}`, texture); }); } private onMeshesLoaded(meshes: any[]): void { meshes.forEach((mesh, index) => { TOOLKIT.PreloadAssetsManager.CacheAsset(`mesh_${index}`, mesh); }); } private onAudioLoaded(sounds: any[]): void { sounds.forEach((sound, index) => { TOOLKIT.PreloadAssetsManager.CacheAsset(`audio_${index}`, sound); }); this.assetsLoaded = true; this.onAllAssetsLoaded(); } private onAllAssetsLoaded(): void { console.log("All assets preloaded successfully!"); console.log(`Cache size: ${TOOLKIT.PreloadAssetsManager.GetCacheSize()} assets`); } } ``` -------------------------------- ### Basic Loading Screen Setup Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/ui/CustomLoadingScreen.md Demonstrates how to initialize and register a CustomLoadingScreen with the Babylon.js engine. Set the background color and ensure the engine is available before assigning the loading screen. ```typescript class LoadingScreenManager extends TOOLKIT.ScriptComponent { public loadingScreen: TOOLKIT.CustomLoadingScreen; protected start(): void { this.setupLoadingScreen(); } private setupLoadingScreen(): void { this.loadingScreen = new TOOLKIT.CustomLoadingScreen( "loading-container", "Loading assets...", true ); this.loadingScreen.loadingUIBackgroundColor = "#000000"; this.registerLoadingScreen(); } private registerLoadingScreen(): void { const engine = TOOLKIT.SceneManager.GetEngine(this.scene); if (engine) { engine.loadingScreen = this.loadingScreen; } } public showLoading(): void { this.loadingScreen.displayLoadingUI(); } public hideLoading(): void { this.loadingScreen.hideLoadingUI(); } } ``` -------------------------------- ### Basic Touch Joystick Setup and Usage Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/input/TouchJoystickHandler.md Sets up a TouchJoystickHandler with customizable properties and event callbacks. It integrates joystick input with character movement in a game loop. ```typescript class MobileController extends TOOLKIT.ScriptComponent { public joystick: TOOLKIT.TouchJoystickHandler; public moveSpeed: number = 5.0; protected start(): void { this.setupTouchJoystick(); } private setupTouchJoystick(): void { this.joystick = new TOOLKIT.TouchJoystickHandler( "joystick-stick", 100, 20, true, TOOLKIT.TouchMouseButton.Left, "joystick-base" ); this.joystick.enabled = true; this.joystick.updateElements = true; this.joystick.preventDefault = true; this.joystick.stopPropagation = true; this.joystick.baseElementOpacity = "0.5"; this.joystick.stickElementOpacity = "0.8"; this.setupJoystickEvents(); } private setupJoystickEvents(): void { this.joystick.onHandleDown = (event) => { console.log("Joystick activated"); }; this.joystick.onHandleMove = (event) => { this.handleMovement(); }; this.joystick.onHandleUp = (event) => { console.log("Joystick released"); }; } protected update(): void { if (this.joystick.isActive()) { this.handleMovement(); } } private handleMovement(): void { const inputX = this.joystick.getInputX(); const inputY = this.joystick.getInputY(); const magnitude = this.joystick.getInputMagnitude(); if (magnitude > 0.1) { const deltaTime = TOOLKIT.SceneManager.GetDeltaTime(); const moveVector = new BABYLON.Vector3(inputX, 0, inputY); moveVector.scaleInPlace(this.moveSpeed * magnitude * deltaTime); this.transform.position.addInPlace(moveVector); } } protected destroy(): void { if (this.joystick) { this.joystick.dispose(); } } } ``` -------------------------------- ### Precise Animation with Start, End, and Yoyo Effects Source: https://github.com/babylonjs/babylontoolkit/blob/master/Tweening/README.md Animates a mesh between specified start and end values for properties, incorporating yoyo effects for reversible animations. Uses TweenFromToAsync for direct control over start and end points. Requires SM alias for SceneManager. ```typescript await SM.TweenFromToAsync( mesh, { "position.x": -2, "position.y": 0 }, // Start values { "position.x": 2, "position.y": 1.5 }, // End values { duration: 2, ease: "quadInOut", yoyo: true, yoyoCount: 1 } ``` -------------------------------- ### Physics Body Implementation Example Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/interfaces/Physics.md Example of implementing the IPhysicsBody interface in a TypeScript component, demonstrating how to configure physics body properties. ```APIDOC ## Physics Body Implementation ### Description Example of implementing the IPhysicsBody interface. ### Code Example ```typescript class PhysicsBodyComponent extends TOOLKIT.ScriptComponent implements TOOLKIT.IPhysicsBody { public mass: number = 1.0; public isKinematic: boolean = false; public useGravity: boolean = true; public linearDamping: number = 0.0; public angularDamping: number = 0.05; public freezePosition: boolean[] = [false, false, false]; public freezeRotation: boolean[] = [false, false, false]; protected start(): void { this.setupPhysicsBody(); } private setupPhysicsBody(): void { console.log(`Physics body configured with mass: ${this.mass}`); } } ``` ``` -------------------------------- ### TouchJoystickHandler Initialization and Configuration Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/input/TouchJoystickHandler.md Demonstrates how to instantiate and configure a TouchJoystickHandler with various properties for visual appearance and behavior. ```APIDOC ## TouchJoystickHandler ### Description Initializes a new instance of the TouchJoystickHandler class. ### Constructor `new TouchJoystickHandler(id: string, size: number, stickSize: number, isCentered: boolean, mouseButton: TouchMouseButton, baseElementId?: string)` - **id** (string) - The unique identifier for the joystick element. - **size** (number) - The overall size of the joystick. - **stickSize** (number) - The size of the joystick's movable stick. - **isCentered** (boolean) - Whether the joystick should be centered. - **mouseButton** (TouchMouseButton) - The mouse button to associate with the joystick. - **baseElementId** (string, optional) - The ID of the HTML element to use as the joystick's base. ### Properties - **enabled** (boolean) - Enables or disables the joystick. - **updateElements** (boolean) - Toggles the updating of joystick visual elements. - **preventDefault** (boolean) - Prevents default browser behavior when the joystick is active. - **stopPropagation** (boolean) - Stops event propagation when the joystick is active. - **baseElementOpacity** (string) - Sets the opacity of the joystick's base element. - **stickElementOpacity** (string) - Sets the opacity of the joystick's stick element. ### Methods - **onHandleDown**: Callback function executed when the joystick handle is pressed. - **onHandleMove**: Callback function executed when the joystick handle is moved. - **onHandleUp**: Callback function executed when the joystick handle is released. - **isActive()**: Returns `true` if the joystick is currently active, `false` otherwise. - **getInputX()**: Returns the current horizontal input value of the joystick. - **getInputY()**: Returns the current vertical input value of the joystick. - **getInputMagnitude()**: Returns the magnitude of the current joystick input. - **dispose()**: Cleans up and disposes of the joystick handler to prevent memory leaks. ``` -------------------------------- ### Animation State Implementation Example Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/interfaces/Animation.md Provides a usage example of implementing the IAnimationState interface within a TypeScript component, demonstrating how to set up animation states and events. ```APIDOC ## Animation State Implementation ### Description Provides a usage example of implementing the IAnimationState interface. ### Code Example ```typescript class AnimationStateComponent extends TOOLKIT.ScriptComponent implements TOOLKIT.IAnimationState { public name: string = "IdleState"; public length: number = 2.0; public speed: number = 1.0; public loop: boolean = true; public clip: BABYLON.AnimationGroup; public events: TOOLKIT.IAnimationEvent[] = []; protected start(): void { this.setupAnimationState(); } private setupAnimationState(): void { this.events.push({ time: 0.5, functionName: "OnAnimationMidpoint", stringParameter: "idle", floatParameter: 0.5, intParameter: 1, objectReferenceParameter: null }); console.log(`Animation state '${this.name}' configured`); } } ``` ``` -------------------------------- ### TweenFromToAsync for Specific Start and End Values Source: https://github.com/babylonjs/babylontoolkit/blob/master/Tweening/README.md Animates properties from explicitly defined start values to specified end values asynchronously. Requires SM alias for SceneManager. ```typescript await SM.TweenFromToAsync( mesh, { "position.y": -10, "material.alpha": 0 }, // Start { "position.y": 0, "material.alpha": 1 }, // End { duration: 1.5, ease: "backOut" } ); ``` -------------------------------- ### Basic State Setup with MachineState Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/animation/MachineState.md Demonstrates how to initialize and configure MachineState instances for 'Idle' and 'Walk' animations within an AnimationController. Includes generating unique state hashes. ```typescript class AnimationController extends TOOLKIT.ScriptComponent { public idleState: TOOLKIT.MachineState = {} as TOOLKIT.MachineState; public walkState: TOOLKIT.MachineState = {} as TOOLKIT.MachineState; protected start(): void { this.setupAnimationStates(); } private setupAnimationStates(): void { this.idleState.name = "Idle"; this.idleState.hash = this.generateStateHash("Idle"); this.idleState.length = 2.0; this.idleState.rate = 1.0; this.idleState.layer = "Base Layer"; this.idleState.layerIndex = 0; this.walkState.name = "Walk"; this.walkState.hash = this.generateStateHash("Walk"); this.walkState.length = 1.5; this.walkState.rate = 1.0; this.walkState.speedParameter = "Speed"; this.walkState.speedParameterActive = true; } private generateStateHash(stateName: string): number { return stateName.split('').reduce((hash, char) => { return ((hash << 5) - hash) + char.charCodeAt(0); }, 0); } } ``` -------------------------------- ### Basic Object Pooling Example Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/utilities/PrefabObjectPool.md Demonstrates how to set up and use a PrefabObjectPool to manage bullet instances. Configure pool properties like name, auto-expansion, initial size, and maximum size. Objects are retrieved, used, and returned to the pool. ```typescript class BasicObjectPoolExample extends TOOLKIT.ScriptComponent { public bulletPool: TOOLKIT.PrefabObjectPool; protected start(): void { this.setupObjectPool(); } private setupObjectPool(): void { const bulletTemplate = BABYLON.MeshBuilder.CreateSphere("bulletTemplate", { diameter: 0.2 }, this.scene); bulletTemplate.setEnabled(false); this.bulletPool = new TOOLKIT.PrefabObjectPool(); this.bulletPool.poolName = "BulletPool"; this.bulletPool.autoExpand = true; this.bulletPool.initialSize = 50; this.bulletPool.maxSize = 200; console.log("Bullet pool created"); } public fireBullet(position: BABYLON.Vector3): void { const bullet = this.bulletPool.getObject(); if (bullet) { bullet.position = position; bullet.setEnabled(true); setTimeout(() => { this.returnBullet(bullet); }, 3000); } } private returnBullet(bullet: BABYLON.TransformNode): void { bullet.setEnabled(false); this.bulletPool.returnObject(bullet); } } ``` -------------------------------- ### Animate BABYLON.js Vector3 Scaling with From/To Source: https://github.com/babylonjs/babylontoolkit/blob/master/Tweening/README.md Animate the scaling of a mesh from a starting Vector3 to an ending Vector3. This allows for precise control over the animation's start and end states. ```typescript // Vector3 scaling with from/to await SM.TweenFromToAsync(mesh, { scaling: new BABYLON.Vector3(1, 1, 1) }, // From { scaling: new BABYLON.Vector3(2, 0.5, 1.5) }, // To { duration: 1.5, ease: "easeInOutElastic" } ); ``` -------------------------------- ### GetTime Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/core/SceneManager.md Get the current time in seconds. ```APIDOC ## GetTime() ### Description Get the current time in seconds. ### Returns `number` - Current time in seconds ``` -------------------------------- ### GetComponents Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/core/SceneManager.md Gets all script components on the transform. ```APIDOC ## GetComponents(transform, recursive?) ### Description Gets all script components on the transform. ### Parameters - `transform` (BABYLON.TransformNode) - The transform node - `recursive?` (boolean) - Search recursively in children ### Returns `TOOLKIT.ScriptComponent[]` - Array of component instances ``` -------------------------------- ### GetDeltaTime Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/core/SceneManager.md Get the current delta time in seconds. ```APIDOC ## GetDeltaTime(scene, applyAnimationRatio?) ### Description Get the current delta time in seconds. ### Parameters - `scene` (BABYLON.Scene) - The scene instance - `applyAnimationRatio?` (boolean) - Apply animation ratio ### Returns `number` - Delta time in seconds ``` -------------------------------- ### Configure Physics Engine and Setup Component Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/physics/RigidbodyPhysics.md Initializes the physics engine for the scene and adds physics to a transform. Ensure the physics engine is configured before adding components. ```typescript // Configure physics engine for the scene await TOOLKIT.RigidbodyPhysics.ConfigurePhysicsEngine(scene, true, 60, 10, true, 0.01); // Add physics to a transform TOOLKIT.RigidbodyPhysics.SetupPhysicsComponent(scene, boxTransform); ``` -------------------------------- ### GetMeshByID Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/core/SceneManager.md Gets the specified mesh by id from scene. ```APIDOC ## GetMeshByID(scene, id) ### Description Gets the specified mesh by id from scene. ### Parameters - `scene` (BABYLON.Scene) - The scene instance - `id` (string) - The mesh id ### Returns `BABYLON.Mesh` - The mesh object ``` -------------------------------- ### GetCacheSize Source: https://github.com/babylonjs/babylontoolkit/blob/master/Reference/api/assets/PreloadAssetsManager.md Gets the current number of cached assets. ```APIDOC ## GetCacheSize ### Description Gets the current number of cached assets. ### Method Signature `GetCacheSize()` ### Returns - `number` - Number of assets in cache ```