### Networking - Mirror (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Illustrates configuring a Character for client authority networking with Mirror. This approach is similar to standalone operation, simplifying initial setup. ```csharp // Placeholder for actual C# code demonstrating ECM2 with Mirror networking ``` -------------------------------- ### Networking - Fusion (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Provides a comprehensive example of integrating ECM2 movement into a networked environment using Fusion. It includes client-side prediction, reconciliation, and efficient data storage using a histogram. ```csharp // Placeholder for actual C# code demonstrating ECM2 with Fusion networking ``` -------------------------------- ### Networking - FishNet (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Shows a basic implementation of ECM2 movement synchronization with FishNet. This example focuses on synchronizing the CharacterMovement component only. ```csharp // Placeholder for actual C# code demonstrating ECM2 with FishNet networking ``` -------------------------------- ### First Person Fly Controls (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Illustrates adding flight controls to a first-person character, building upon the previous first-person example. It shows how to manage movement in a flying state. ```csharp // Placeholder for actual C# code demonstrating first-person fly controls ``` -------------------------------- ### CharacterInput Script for Character Control in Unity Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/getting-started This C# script, designed for Unity, handles player input for character movement, jumping, and crouching. It uses the Character component to execute these actions. The movement direction is determined by horizontal and vertical input axes and can be made relative to the camera's view direction. It depends on the UnityEngine and ECM2 namespaces. ```csharp using UnityEngine; using ECM2; namespace ECM2.Examples { public class CharacterInput : MonoBehaviour { // The controlled Character private Character _character; private void Awake() { // Cache controlled character _character = GetComponent(); } private void Update() { // Poll movement input Vector2 inputMove = new Vector2() { x = Input.GetAxisRaw("Horizontal"), y = Input.GetAxisRaw("Vertical") }; // Compose a movement direction vector in world space Vector3 movementDirection = Vector3.zero; movementDirection += Vector3.right * inputMove.x; movementDirection += Vector3.forward * inputMove.y; // If character has a camera assigned, // make movement direction relative to this camera view direction if (_character.camera) { movementDirection = movementDirection.relativeTo(_character.cameraTransform); } // Set character's movement direction vector _character.SetMovementDirection(movementDirection); // Crouch input if (Input.GetKeyDown(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.C)) _character.Crouch(); else if (Input.GetKeyUp(KeyCode.LeftControl) || Input.GetKeyUp(KeyCode.C)) _character.UnCrouch(); // Jump input if (Input.GetButtonDown("Jump")) _character.Jump(); else if (Input.GetButtonUp("Jump")) _character.StopJumping(); } } } ``` -------------------------------- ### Photon Fusion 2 Initialization Fix (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/change-log A bug fix in ECM2 v1.4.2 resolves an issue in Photon Fusion 2 examples where `NetworkData` was not always initialized correctly. This ensures proper setup for networking components in Fusion 2 projects. ```csharp // Version 1.4.2 // Bug Fixes: // Photon Fusion 2 Initialization: Fixed an issue in Photon Fusion 2 examples where `NetworkData` was sometimes not initialized under specific conditions. ``` -------------------------------- ### First Person Swim Controls (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Shows how to implement swimming controls for a first-person character, extending the first-person example. This focuses on underwater or swimming movement mechanics. ```csharp // Placeholder for actual C# code demonstrating first-person swim controls ``` -------------------------------- ### Networking - NetCode for GameObjects (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Demonstrates how to configure a Character for client authority networking using NetCode for GameObjects. Similar to Mirror, it offers a straightforward integration. ```csharp // Placeholder for actual C# code demonstrating ECM2 with NetCode for GameObjects ``` -------------------------------- ### Networking Examples Update (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/change-log Version 1.4.1 includes updated networking examples for the latest versions of popular networking solutions like Fusion, FishNet, Mirror, and NetCode. This ensures compatibility and demonstrates current best practices for multiplayer implementation with ECM2. ```csharp // Version 1.4.1 // Added networking examples for the latest versions of Fusion, FishNet, Mirror, and NetCode. ``` -------------------------------- ### Input System Example (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/change-log ECM2 v1.4.1 introduced an Input System example, demonstrating how to integrate ECM2 with Unity's new Input System for character control. This allows developers to leverage modern input management practices. ```csharp // Version 1.4.1 // Added Input system example. ``` -------------------------------- ### Basic Teleport System (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Shows how to implement a basic teleport system for a Character, including teleporting the character and adjusting its rotation to match the teleporter's orientation. ```csharp // Placeholder for actual C# code demonstrating basic teleport system ``` -------------------------------- ### Side-Scrolling Movement (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Illustrates configuring and implementing typical 2D side-scrolling character movement. This example focuses on the specific mechanics required for 2D platformers. ```csharp // Placeholder for actual C# code demonstrating side-scrolling movement ``` -------------------------------- ### Third-Person Character Controller (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Provides a practical demonstration of implementing a basic third-person character controller in Unity. It covers character movement, camera rotation, and zoom, with customizable parameters. ```csharp // Placeholder for actual C# code demonstrating third-person controller ``` -------------------------------- ### First Person Character Movement (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Demonstrates extending the base Character class to implement standard first-person movement controls. This example shows inheritance for custom character behavior. ```csharp // Placeholder for actual C# code demonstrating first-person movement ``` -------------------------------- ### Ladder Climbing Mechanics (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Demonstrates implementing ladder climbing by extending a Character through composition, introducing a new 'Climbing' custom movement mode. This shows how to add distinct movement states. ```csharp // Placeholder for actual C# code demonstrating ladder climbing mechanics ``` -------------------------------- ### Custom Jump Ability (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Illustrates replacing the built-in jump functionality of the Character class to create a custom jump ability. This example reproduces jump behavior from earlier versions (pre-v1.4.0). ```csharp // Placeholder for actual C# code demonstrating a custom jump ability ``` -------------------------------- ### Character Class Refactoring and Features in Easy Character Movement 2 Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/change-log The Character class has been refactored for extension via composition. Input code has been removed, sprint functionality is now an example, and jump has been reworked. MovementMode and RotationMode enums are now part of the Character class, and deltaTime is a parameter. Method names have been updated for clarity, and the Move method is removed. The Simulation method is split into inner methods and events. FirstPersonCharacter, ThirdPersonCharacter are now examples, and AgentCharacter is replaced by NavMeshCharacter for NavMesh navigation. ```csharp public enum MovementMode { Walking, Falling, Sprinting, Sliding, Crouching } public enum RotationMode { OrientRotationToMovement, OrientRotationToPreviousMovement, OrientRotationToPlayerInput } public class Character { // Example usage: public void SetMovementMode(MovementMode mode) { /* ... */ } public void SetRotationMode(RotationMode mode) { /* ... */ } } ``` -------------------------------- ### Glide Ability via Composition (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Demonstrates implementing a Glide ability using composition, influencing character behavior through 'hook' methods without inheriting from the Character class. This highlights a flexible approach to adding abilities. ```csharp // Placeholder for actual C# code demonstrating glide ability via composition ``` -------------------------------- ### Toggle Gravity Direction (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Demonstrates extending a Character via composition to enable toggling gravity direction and orienting the character along the world-up defined by the current gravity direction. This allows for dynamic gravity changes. ```csharp // Placeholder for actual C# code demonstrating toggle gravity direction ``` -------------------------------- ### Slide Mechanic Implementation (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Shows how to extend a Character via inheritance to implement a slide mechanic, realized as a new 'Sliding' custom movement mode. This focuses on adding a sliding action. ```csharp // Placeholder for actual C# code demonstrating slide mechanic ``` -------------------------------- ### Planet Walk Movement (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Demonstrates extending a Character via inheritance to modify gravity and orientation, mimicking planet curvature movement like in Mario Galaxy. This involves custom gravity and rotation logic. ```csharp // Placeholder for actual C# code demonstrating planet walk movement ``` -------------------------------- ### Transparent Platform Support Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general Provides first-class support for animated, scripted, or physics-based platforms without requiring additional setup. Characters interact seamlessly with these dynamic platforms. ```csharp using UnityEngine; public class PlatformInteraction : MonoBehaviour { // Logic to handle character movement on and off various platform types void OnControllerColliderHit(ControllerColliderHit hit) { // Check if the hit collider is a platform // Adjust character's velocity/parent based on platform movement } } ``` -------------------------------- ### Swimming Example with Jump Out of Water (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/change-log Version 1.4.1 features an updated swimming example in ECM2 that showcases the implementation of a jump-out-of-water mechanic. This provides a practical demonstration of character interaction with water volumes. ```csharp // Version 1.4.1 // Updated swimming example. This demonstrates the implementation of a jump out of water. ``` -------------------------------- ### One-Way Platform Implementation (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/walkthrough/moving-platforms This example shows how to create a one-way platform that allows a character to pass through from one side but not the other. It uses OnTriggerEnter and OnTriggerExit to manage collision between the character and the platform. ```csharp public class OneWayPlatform : MonoBehaviour { public Collider platformCollider; private void OnTriggerEnter(Collider other) { if (!other.CompareTag("Player")) return; Character character = other.GetComponent(); if (character) character.IgnoreCollision(platformCollider); } private void OnTriggerExit(Collider other) { if (!other.CompareTag("Player")) return; Character character = other.GetComponent(); if (character) character.IgnoreCollision(platformCollider, false); } } ``` -------------------------------- ### Managing Character Movement Mode (Flying Example) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/components/character Demonstrates how to programmatically set the character's movement mode. It includes entering the Flying mode and exiting it by transitioning to the Falling mode. ```csharp // Enter flying mode SetMovementMode(MovementMode.Flying); .. // Exits flying mode SetMovementMode(MovementMode.Falling); ``` -------------------------------- ### Orient Character to Ground Contour (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Shows how to orient a Character to follow the contour of terrain by sampling an area to compute an average normal, then adjusting the character's rotation. This ensures the character stays aligned with the ground. ```csharp // Placeholder for actual C# code demonstrating orienting character to ground ``` -------------------------------- ### Character Position and Rotation API Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/components/character-movement Methods for getting and setting the character's position and rotation in world space. ```APIDOC ## GET /api/character/position ### Description Returns the character's current position. ### Method GET ### Endpoint /api/character/position ### Response #### Success Response (200) - **position** (Vector3) - The character's current position. #### Response Example { "position": { "x": 0.0, "y": 1.0, "z": 0.0 } } ``` ```APIDOC ## PUT /api/character/position ### Description Updates the character's current position. Optionally finds and updates the character's ground result if `updateGround` is true. ### Method PUT ### Endpoint /api/character/position ### Parameters #### Request Body - **newPosition** (Vector3) - Required - The new position for the character. - **updateGround** (bool) - Optional - If true, updates the character's ground result. ### Request Example { "newPosition": { "x": 1.0, "y": 1.0, "z": 1.0 }, "updateGround": true } ### Response #### Success Response (200) - **message** (string) - Indicates successful update. #### Response Example { "message": "Character position updated successfully." } ``` ```APIDOC ## GET /api/character/rotation ### Description Returns the character's current rotation. ### Method GET ### Endpoint /api/character/rotation ### Response #### Success Response (200) - **rotation** (Quaternion) - The character's current rotation. #### Response Example { "rotation": { "x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0 } } ``` ```APIDOC ## PUT /api/character/rotation ### Description Updates the character's current rotation. ### Method PUT ### Endpoint /api/character/rotation ### Parameters #### Request Body - **newRotation** (Quaternion) - Required - The new rotation for the character. ### Request Example { "newRotation": { "x": 0.0, "y": 0.707, "z": 0.0, "w": 0.707 } } ### Response #### Success Response (200) - **message** (string) - Indicates successful update. #### Response Example { "message": "Character rotation updated successfully." } ``` ```APIDOC ## PUT /api/character/position-rotation ### Description Sets the world space position and rotation of the character. If `updateGround` is true, it will find for ground and update the character's current ground result. ### Method PUT ### Endpoint /api/character/position-rotation ### Parameters #### Request Body - **newPosition** (Vector3) - Required - The new position for the character. - **newRotation** (Quaternion) - Required - The new rotation for the character. - **updateGround** (bool) - Optional - If true, updates the character's ground result. ### Request Example { "newPosition": { "x": 1.0, "y": 1.0, "z": 1.0 }, "newRotation": { "x": 0.0, "y": 0.707, "z": 0.0, "w": 0.707 }, "updateGround": true } ### Response #### Success Response (200) - **message** (string) - Indicates successful update. #### Response Example { "message": "Character position and rotation updated successfully." } ``` -------------------------------- ### Apply Landing Force to Ground Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/walkthrough/physics Shows how to extend the Character component to apply a force to the ground when the character lands. This example uses the Landed event and calculates the force based on character mass, gravity, and landing velocity. It requires the Character component and a Rigidbody on the ground. ```csharp public class ApplyLandingForce : MonoBehaviour { public float landingForceScale = 1.0f; private Character _character; private void Awake() { _character = GetComponent(); } private void OnEnable() { _character.Landed += OnLanded; } private void OnDisable() { _character.Landed -= OnLanded; } private void OnLanded(Vector3 landingVelocity) { Rigidbody groundRigidbody = _character.characterMovement.groundRigidbody; if (!groundRigidbody) return; Vector3 force = _character.GetGravityVector() * (_character.mass * landingVelocity.magnitude * landingForceScale); groundRigidbody.AddForceAtPosition(force, _character.position); } } ``` -------------------------------- ### Scripted Dynamic Platform Movement (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/walkthrough/moving-platforms This code snippet demonstrates how to implement the movement logic for a scripted dynamic platform using the FixedUpdate method. It utilizes Vector3.Lerp for smooth interpolation between start and target positions. ```csharp public void FixedUpdate() { float t = EaseInOut(Mathf.PingPong(Time.time, _moveTime), _moveTime); Vector3 p = Vector3.Lerp(_startPosition, _targetPosition, t); _rigidbody.MovePosition(p); } ``` -------------------------------- ### Iterating Through Collisions Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/components/character Provides an example of how to iterate through all collision results detected during the last CharacterMovement.Move invocation using GetCollisionCount and GetCollisionResult. ```csharp for (int i = 0, c = characterMovement.GetCollisionCount(); i < c; i++) { CollisionResult collisionResult = characterMovement.GetCollisionResult(i); // Handle collision here... } ``` -------------------------------- ### Slope Speed Modifier (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/examples Demonstrates using the `GetSignedSlopeAngle` function (v1.4.0+) to adjust character movement speed based on the slope angle. This allows for dynamic speed changes on inclines and declines. ```csharp // Placeholder for actual C# code demonstrating slope speed modifier ``` -------------------------------- ### Implement Sprint Ability with Composition Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/walkthrough/extending-a-character Implements a `SprintAbility` script using composition to add sprinting functionality to a character. It utilizes the `BeforeSimulationUpdated` event to modify `maxWalkSpeed` and includes methods for starting, stopping, and checking the sprint state. This script requires a `Character` component. ```csharp /// /// This example shows how to extend a Character (through composition) to perform a sprint ability. /// This one use the new simulation OnBeforeSimulationUpdate event (introduced in v1.4), /// to easily modify the character's state within Character's simulation loop. /// public class SprintAbility : MonoBehaviour { [Space(15.0f)] public float maxSprintSpeed = 10.0f; private Character _character; private bool _isSprinting; private bool _sprintInputPressed; private float _cachedMaxWalkSpeed; /// /// Request the character to start to sprint. /// public void Sprint() { _sprintInputPressed = true; } /// /// Request the character to stop sprinting. /// public void StopSprinting() { _sprintInputPressed = false; } public bool IsSprinting() { return _isSprinting; } private bool CanSprint() { return _character.IsWalking() && !_character.IsCrouched(); } private void CheckSprintInput() { if (!_isSprinting && _sprintInputPressed && CanSprint()) { _isSprinting = true; _cachedMaxWalkSpeed = _character.maxWalkSpeed; _character.maxWalkSpeed = maxSprintSpeed; } else if (_isSprinting && (!_sprintInputPressed || !CanSprint())) { _isSprinting = false; _character.maxWalkSpeed = _cachedMaxWalkSpeed; } } private void OnBeforeSimulationUpdated(float deltaTime) { // Handle sprinting CheckSprintInput(); } private void Awake() { // Cache character _character = GetComponent(); } private void OnEnable() { // Subscribe to Character BeforeSimulationUpdated event _character.BeforeSimulationUpdated += OnBeforeSimulationUpdated; } private void OnDisable() { // Un-Subscribe from Character BeforeSimulationUpdated event _character.BeforeSimulationUpdated -= OnBeforeSimulationUpdated; } } ``` -------------------------------- ### Character Jump and Apex Notification Example Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/components/character Demonstrates how to override the OnJumped and OnReachedJumpApex methods in a derived Character class. It shows how to call the base implementation, add custom logic, and enable jump apex notifications. ```csharp protected override void OnJumped() { // Call base method implementation base.OnJumped(); // Add your code here... Debug.Log("Jumped!"); // Enable apex notification event notifyJumpApex = true; } protected override void OnReachedJumpApex() { // Call base method implementation base.OnReachedJumpApex(); // Add your code here... Debug.Log($"Apex reached {GetVelocity():F4}"); } ``` -------------------------------- ### Get Collision Result Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/components/character-movement Retrieves a specific collision result from the list of collisions detected in the last Move call, using an index to specify which result to get. ```csharp public CollisionResult GetCollisionResult(int index) { // ... implementation details ... return new CollisionResult(); } ``` -------------------------------- ### Get Collision Count Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/components/character-movement Retrieves the number of collisions detected during the last call to the Move method. ```csharp public int GetCollisionCount() { // ... implementation details ... return 0; } ``` -------------------------------- ### Character Force and Movement API Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/components/character-movement Methods for applying forces, launching, and moving the character. ```APIDOC ## POST /api/character/add-force ### Description Adds a force to the Character. This force will be accumulated and applied during the `Move` method call. ### Method POST ### Endpoint /api/character/add-force ### Parameters #### Request Body - **force** (Vector3) - Required - The force vector to apply. - **forceMode** (ForceMode) - Optional - The mode in which to apply the force. Defaults to ForceMode.Force. ### Request Example { "force": { "x": 0.0, "y": 10.0, "z": 0.0 }, "forceMode": "Impulse" } ### Response #### Success Response (200) - **message** (string) - Indicates successful force application. #### Response Example { "message": "Force added successfully." } ``` ```APIDOC ## POST /api/character/add-explosion-force ### Description Applies a force to this Character that simulates explosion effects. The force decreases in proportion to the distance from the origin, unless the radius is zero. ### Method POST ### Endpoint /api/character/add-explosion-force ### Parameters #### Request Body - **strength** (float) - Required - The magnitude of the explosion force. - **origin** (Vector3) - Required - The center position of the explosion in world space. - **radius** (float) - Required - The radius of the explosion. If zero, the full force is applied regardless of distance. - **forceMode** (ForceMode) - Optional - The mode in which to apply the force. Defaults to ForceMode.Force. ### Request Example { "strength": 50.0, "origin": { "x": 5.0, "y": 1.0, "z": 5.0 }, "radius": 10.0, "forceMode": "Force" } ### Response #### Success Response (200) - **message** (string) - Indicates successful force application. #### Response Example { "message": "Explosion force applied successfully." } ``` ```APIDOC ## POST /api/character/launch ### Description Sets a pending launch velocity on the Character. This velocity will be processed in the next `Move` call. ### Method POST ### Endpoint /api/character/launch ### Parameters #### Request Body - **launchVelocity** (Vector3) - Required - The desired launch velocity. - **overrideVerticalVelocity** (bool) - Optional - If true, replaces the vertical component of the Character's velocity instead of adding to it. Defaults to false. - **overrideLateralVelocity** (bool) - Optional - If true, replaces the XY part of the Character's velocity instead of adding to it. Defaults to false. ### Request Example { "launchVelocity": { "x": 0.0, "y": 5.0, "z": 0.0 }, "overrideVerticalVelocity": true, "overrideLateralVelocity": false } ### Response #### Success Response (200) - **message** (string) - Indicates successful launch velocity setting. #### Response Example { "message": "Launch velocity set successfully." } ``` ```APIDOC ## POST /api/character/move ### Description Moves the character along its current velocity. This performs collision-constrained movement, resolving any collisions or overlaps found during movement. ### Method POST ### Endpoint /api/character/move ### Parameters #### Request Body - **deltaTime** (float) - Required - The simulation delta time. ### Request Example { "deltaTime": 0.016 } ### Response #### Success Response (200) - **collisionFlags** (CollisionFlags) - Flags indicating the result of the collision detection during movement. #### Response Example { "collisionFlags": "None" } ``` ```APIDOC ## POST /api/character/move-with-velocity ### Description Moves the character along the given velocity vector. ### Method POST ### Endpoint /api/character/move-with-velocity ### Parameters #### Request Body - **velocity** (Vector3) - Required - The velocity vector to move the character along. ### Request Example { "velocity": { "x": 1.0, "y": 0.0, "z": 0.0 } } ### Response #### Success Response (200) - **message** (string) - Indicates successful movement. #### Response Example { "message": "Character moved successfully." } ``` -------------------------------- ### Character Input Handling with Unity Input System Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/walkthrough/controlling-a-character This C# script demonstrates how to handle character input using Unity's new Input System. It includes event handlers for movement, jump, and crouch actions, leveraging the PlayerInput component to manage input processing and event triggering. ```csharp using ECM2; using UnityEngine; using UnityEngine.InputSystem; public class CharacterInput : MonoBehaviour { // Cached controlled character private Character _character; /// /// Movement InputAction event handler. /// public void OnMove(InputAction.CallbackContext context) { // Read input values Vector2 inputMovement = context.ReadValue(); // Compose a movement direction vector in world space Vector3 movementDirection = Vector3.zero; movementDirection += Vector3.forward * inputMovement.y; movementDirection += Vector3.right * inputMovement.x; // If character has a camera assigned, // make movement direction relative to this camera view direction if (_character.camera) { movementDirection = movementDirection.relativeTo(_character.cameraTransform); } // Set character's movement direction vector _character.SetMovementDirection(movementDirection); } /// /// Jump InputAction event handler. /// public void OnJump(InputAction.CallbackContext context) { if (context.started) _character.Jump(); else if (context.canceled) _character.StopJumping(); } /// /// Crouch InputAction event handler. /// public void OnCrouch(InputAction.CallbackContext context) { if (context.started) _character.Crouch(); else if (context.canceled) _character.UnCrouch(); } private void Awake() { // // Cache controlled character. _character = GetComponent(); } } ``` -------------------------------- ### Get Character Rotation Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/components/character-movement Retrieves the current world space rotation of the character. Returns a Quaternion representing the character's orientation. ```csharp /// /// Returns the character current rotation. /// public Quaternion GetRotation() ``` -------------------------------- ### Get Character Position Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/components/character-movement Retrieves the current world space position of the character. Returns a Vector3 representing the character's location. ```csharp /// /// Returns the character current position. /// public Vector3 GetPosition() ``` -------------------------------- ### Get Plane Constraint Normal Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/components/character-movement Returns the normal vector of the current plane constraint. This is used to understand the orientation of the constrained movement plane. ```csharp /// /// Current plane constraint normal. /// public Vector3 GetPlaneConstraintNormal() ``` -------------------------------- ### Character Attachment and Ground Constraint API Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/components/character-movement Methods for attaching the character to platforms and managing ground constraints. ```APIDOC ## POST /api/character/attach-to ### Description Allows explicit attachment of this character to a moving 'platform' so it no longer depends on the ground state. ### Method POST ### Endpoint /api/character/attach-to ### Parameters #### Request Body - **parent** (Rigidbody) - Required - The Rigidbody component of the platform to attach to. ### Request Example { "parent": { "rigidbody_id": "some_rigidbody_identifier" } } ### Response #### Success Response (200) - **message** (string) - Indicates successful attachment. #### Response Example { "message": "Character attached successfully." } ``` ```APIDOC ## POST /api/character/pause-ground-constraint ### Description Temporarily disables ground constraint, allowing the Character to freely leave the ground (e.g., for LaunchCharacter, Jump, etc.). ### Method POST ### Endpoint /api/character/pause-ground-constraint ### Parameters #### Request Body - **unconstrainedTime** (float) - Optional - The duration for which the ground constraint will be paused. Defaults to 0.1f. ### Request Example { "unconstrainedTime": 0.2 } ### Response #### Success Response (200) - **message** (string) - Indicates successful pausing of ground constraint. #### Response Example { "message": "Ground constraint paused successfully." } ``` -------------------------------- ### Configurable Walkable Area with Perch Offset Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general Enhances configurability by allowing customization of the character's 'feet' radius. The `perchOffset` feature helps in fine-tuning how the character interacts with surfaces and maintains stability. ```csharp using UnityEngine; public class CharacterMovement : MonoBehaviour { public float perchOffset = 0.1f; // ... other properties void UpdateMovement() { // Logic that uses perchOffset for ground interaction } } ``` -------------------------------- ### Handle Sprint Input Events Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/walkthrough/extending-a-character Handles player input for sprinting by calling the `Sprint` and `StopSprinting` methods of the `SprintAbility` component. This example demonstrates how to integrate the sprint functionality with keyboard input (LeftShift). ```csharp private SprintAbility _sprintAbility; private void Update() { .. if (Input.GetKeyDown(KeyCode.LeftShift)) _sprintAbility.Sprint(); else if (Input.GetKeyUp(KeyCode.LeftShift)) _sprintAbility.StopSprinting(); } ``` -------------------------------- ### Character Simulation Method - C# Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/components/character The core 'Simulate' method orchestrates the character's movement updates. It calls helper methods to prepare for simulation, perform the main simulation logic, handle post-simulation updates, and finally apply the movement via the CharacterMovement component. This ensures a structured and sequential update process. ```csharp public void Simulate(float deltaTime) { if (isPaused) return; BeforeSimulationUpdate(deltaTime); SimulationUpdate(deltaTime); AfterSimulationUpdate(deltaTime); CharacterMovementUpdate(deltaTime); } ``` -------------------------------- ### Define Custom Sprintable Character (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/walkthrough/extending-a-character This snippet shows the basic structure of a custom character class that inherits from the base Character class. It's a starting point for adding new abilities. ```csharp public class SprintableCharacter : Character { // TODO } ``` -------------------------------- ### Root Motion Support for Animations Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general Incorporates root motion support, allowing character animations to drive movement. This provides more realistic and integrated character animation workflows. ```csharp using UnityEngine; public class RootMotionHandler : MonoBehaviour { private Animator animator; private Vector3 rootMotionDelta; void Awake() { animator = GetComponent(); } void OnAnimatorMove() { rootMotionDelta = animator.deltaPosition; // Apply rootMotionDelta to character movement transform.position += rootMotionDelta; } } ``` -------------------------------- ### Character Simulation - BeforeSimulationUpdate - C# Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/components/character The 'BeforeSimulationUpdate' method prepares the character for movement simulation. It handles automatic switching between movement modes like Walking and Falling based on grounding status, manages jump and crouch actions, and triggers the 'OnBeforeSimulationUpdate' event for custom extensions. ```csharp private void BeforeSimulationUpdate(float deltaTime) ``` -------------------------------- ### Subscribe to Collided Event (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/walkthrough/collision-detection-and-events Shows how to subscribe to the Collided event of a Character instance to handle collision events. This approach is used when extending a Character through composition. ```csharp public class PlayerController : MonoBehaviour { // The controlled Character private Character _character; protected void OnCollided(ref CollisionResult collisionResult) { Debug.Log($"Collided with {collisionResult.collider.name}"); } private void OnEnable() { // Subscribe to Character events _character.Collided += OnCollided; } private void OnDisable() { // Un-subscribe from Character events _character.Collided -= OnCollided; } } ``` -------------------------------- ### Root Motion Controller Public Methods (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/components/root-motion-controller Provides essential public methods for the Root Motion Controller component in Unity. These methods allow flushing accumulated deltas and consuming root motion velocity and rotation, crucial for character movement synchronization. ```csharp /// /// Flush any accumulated deltas. /// This prevents accumulation while character is toggling root motion. /// public virtual void FlushAccumulatedDeltas() /// /// Return current root motion rotation and clears accumulated delta rotation. /// public virtual Quaternion ConsumeRootMotionRotation() /// /// Return current root motion velocity and clears accumulated delta positions. /// public virtual Vector3 ConsumeRootMotionVelocity(float deltaTime) ``` -------------------------------- ### Control Character with Custom Class (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/walkthrough/controlling-a-character Demonstrates how to extend the Character class by inheriting from it and adding input management for movement, jumping, and crouching. ```csharp /// /// This example shows how to extend a Character (through inheritance) /// adding input management. /// public class PlayerCharacter : Character { private void Update() { // Movement input Vector2 inputMove = new Vector2() { x = Input.GetAxisRaw("Horizontal"), y = Input.GetAxisRaw("Vertical") }; Vector3 movementDirection = Vector3.zero; movementDirection += Vector3.right * inputMove.x; movementDirection += Vector3.forward * inputMove.y; // If character has a camera assigned... if (camera) { // Make movement direction relative to its camera view direction movementDirection = movementDirection.relativeTo(cameraTransform); } SetMovementDirection(movementDirection); // Crouch input if (Input.GetKeyDown(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.C)) Crouch(); else if (Input.GetKeyUp(KeyCode.LeftControl) || Input.GetKeyUp(KeyCode.C)) UnCrouch(); // Jump input if (Input.GetButtonDown("Jump")) Jump(); else if (Input.GetButtonUp("Jump")) StopJumping(); } } ``` -------------------------------- ### Integrate Sprint Logic with Simulation Update (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/walkthrough/extending-a-character This code overrides the OnBeforeSimulationUpdate method to call the CheckSprintInput method, ensuring the sprint state is updated every simulation step. It also calls the base method for compatibility. ```csharp protected override void OnBeforeSimulationUpdate(float deltaTime) { // Call base method implementation base.OnBeforeSimulationUpdate(deltaTime); // Handle sprint CheckSprintInput(); } ``` -------------------------------- ### Control Character with External Script (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/walkthrough/controlling-a-character Illustrates how to control a character from an external script (CharacterInput) by accessing its methods for movement, jumping, and crouching. ```csharp using UnityEngine; using ECM2; public class CharacterInput : MonoBehaviour { // The controlled Character private Character _character; private void Awake() { // Cache controlled character _character = GetComponent(); } private void Update() { // Poll movement input Vector2 inputMove = new Vector2() { x = Input.GetAxisRaw("Horizontal"), y = Input.GetAxisRaw("Vertical") }; // Compose a movement direction vector in world space Vector3 movementDirection = Vector3.zero; movementDirection += Vector3.right * inputMove.x; movementDirection += Vector3.forward * inputMove.y; // If character has a camera assigned, // make movement direction relative to this camera view direction if (_character.camera) { movementDirection = movementDirection.relativeTo(_character.cameraTransform); } // Set character's movement direction vector _character.SetMovementDirection(movementDirection); // Crouch input if (Input.GetKeyDown(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.C)) _character.Crouch(); else if (Input.GetKeyUp(KeyCode.LeftControl) || Input.GetKeyUp(KeyCode.C)) _character.UnCrouch(); // Jump input if (Input.GetButtonDown("Jump")) _character.Jump(); else if (Input.GetButtonUp("Jump")) _character.StopJumping(); } } ``` -------------------------------- ### Implement Sprint Ability Logic (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/walkthrough/extending-a-character This code defines the logic for the sprint ability within a custom character class. It includes methods to start and stop sprinting, check sprint conditions, and manage sprint input. ```csharp public class SprintableCharacter : Character { [Space(15.0f)] public float maxSprintSpeed = 10.0f; private bool _isSprinting; private bool _sprintInputPressed; public void Sprint() { _sprintInputPressed = true; } public void StopSprinting() { _sprintInputPressed = false; } public bool IsSprinting() { return _isSprinting; } private bool CanSprint() { // A character can only sprint if: // A character is in its walking movement mode and not crouched return IsWalking() && !IsCrouched(); } private void CheckSprintInput() { if (!_isSprinting && _sprintInputPressed && CanSprint()) { _isSprinting = true; } else if (_isSprinting && (!_sprintInputPressed || !CanSprint())) { _isSprinting = false; } } } ``` -------------------------------- ### Callbacks Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/components/character-movement Defines callbacks for customizing collider interactions and collision responses. ```APIDOC ## Callbacks ### ColliderFilterCallback #### Description Defines a callback to determine if the character should collide with a given collider. #### Parameters - **collider** (Collider) - The collider to check. #### Returns - **boolean** - True to filter (ignore) the collider, false to collide with it. ### CollisionBehaviourCallback #### Description Defines a callback to specify the character's behavior when colliding with a collider. #### Parameters - **collider** (Collider) - The collided collider. #### Returns - **CollisionBehaviour** - The desired collision behavior flags. ### CollisionResponseCallback #### Description Allows modification of the collision response with dynamic objects, such as computing resultant impulse and application point. #### Parameters - **inCollisionResult** (CollisionResult) - The collision result information. - **characterImpulse** (Vector3) - The impulse applied to the character. - **otherImpulse** (Vector3) - The impulse applied to the other object. ``` -------------------------------- ### Collision and Grounding Events Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual The system provides comprehensive collision and grounding events, allowing developers to react to specific interactions. These events offer enhanced control and feedback for character movement. ```csharp public class CollisionEvents : MonoBehaviour { public event Action OnCollisionEnter; public event Action OnCollisionStay; public event Action OnCollisionExit; public event Action OnGroundEnter; public event Action OnGroundStay; public event Action OnGroundExit; // ... (methods to trigger these events based on physics callbacks) } public struct GroundHitInfo { public Vector3 Normal; public Collider GroundCollider; } ``` -------------------------------- ### Launch Character with Bouncer Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/walkthrough/physics Demonstrates using the Character LaunchCharacter function to create a bouncer effect. It applies an impulse to the character upon entering a trigger, optionally overriding vertical and lateral velocities. Requires the Character component and a Collider. ```csharp public class Bouncer : MonoBehaviour { public float launchImpulse = 15.0f; public bool overrideVerticalVelocity; public bool overrideLateralVelocity; private void OnTriggerEnter(Collider other) { if (!other.CompareTag("Player")) return; if (!other.TryGetComponent(out Character character)) return; character.PauseGroundConstraint(); character.LaunchCharacter(transform.up * launchImpulse, overrideVerticalVelocity, overrideLateralVelocity); } } ``` -------------------------------- ### Click-to-Move Character Movement with NavMeshCharacter (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/walkthrough/ai-navigation This C# script enables a character to move to a clicked destination on the ground using the NavMeshCharacter component. It requires a reference to the main camera, the character with NavMeshCharacter, and a ground layer mask. The script casts a ray from the mouse position to detect the ground and then instructs the character to move. ```csharp public class ClickToMove : MonoBehaviour { public Camera mainCamera; public Character character; public LayerMask groundMask; private NavMeshCharacter _navMeshCharacter; private void Awake() { _navMeshCharacter = character.GetComponent(); } private void Update() { if (Input.GetMouseButton(0)) { Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out RaycastHit hitResult, Mathf.Infinity, groundMask)) _navMeshCharacter.MoveToDestination(hitResult.point); } } } ``` -------------------------------- ### Physics Interaction Configuration (C#) Source: https://oscar-gracian.gitbook.io/easy-character-movement-2/user-manual/general/components/character-movement Properties to control character interaction with other rigidbodies and characters, including enabling interaction and scaling push force. ```csharp /// /// If enabled, the player will interact with dynamic rigidbodies when walking into them. /// public bool enablePhysicsInteraction /// /// If enabled, the player will interact with other characters when walking into them. /// public bool physicsInteractionAffectsCharacters /// /// Force applied to rigidbodies when walking into them (due to mass and relative velocity) is scaled by this amount. /// public float pushForceScale ```