Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Get current upwards velocity and set it to zero.

Discussion in 'Scripting' started by TheDuples, Jun 21, 2022.

  1. TheDuples

    TheDuples

    Joined:
    Nov 13, 2018
    Posts:
    39
    I'm trying to implement a double jump in my 3D platformer. At the beginning of each jump I would normally set velocity.y to zero, solving my issue, however my controller has the ability to walk up walls, therefore making velocity.y not what it normally would be. Based on this code, how would I zero out the current upwards velocity based on the normal of a surface at the beginning of a jump, allowing me to properly double jump?

    Code (CSharp):
    1. void Jump(Vector3 gravity) {
    2.         Vector3 jumpDirection;
    3.         if (OnGround) {
    4.             jumpDirection = contactNormal;
    5.         }
    6.         else if (OnSteep) {
    7.             jumpDirection = steepNormal;
    8.             jumpPhase = 0;
    9.         }
    10.         else if (maxAirJumps > 0 && jumpPhase <= maxAirJumps) {
    11.             if (jumpPhase == 0)
    12.             {
    13.                 jumpPhase = 1;
    14.             }
    15.             jumpDirection = contactNormal;
    16.         }
    17.         else {
    18.             return;
    19.         }
    20.  
    21.         stepsSinceLastJump = 0;
    22.         jumpPhase += 1;
    23.         float jumpSpeed = Mathf.Sqrt(2f * gravity.magnitude * jumpHeight);
    24.         jumpDirection = (jumpDirection + upAxis).normalized;
    25.         float alignedSpeed = Vector3.Dot(velocity, jumpDirection);
    26.         if (alignedSpeed > 0f) {
    27.             jumpSpeed = Mathf.Max(jumpSpeed - alignedSpeed, 0f);
    28.         }
    29.         velocity += jumpDirection * jumpSpeed;    
    30.     }
     
    Last edited: Jun 21, 2022
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,596
    Dot product with normal and velocity, then subtract from original velocity, I believe?
     
  3. TheDuples

    TheDuples

    Joined:
    Nov 13, 2018
    Posts:
    39
    It wasn't quite what I was looking for but it did lead me in the right direction, so thank you. This was the code I ended up using:
    Code (CSharp):
    1. velocity = velocity - Vector3.Project(velocity, transform.up);
     
    RadRedPanda likes this.