Search Unity

Question Completely lost on adding a jump buffer and coyote time.

Discussion in 'Scripting' started by blepomorph, May 19, 2023.

  1. blepomorph

    blepomorph

    Joined:
    Apr 5, 2023
    Posts:
    1
    Hey everyone. This is my first post here. If there is a more properly location to be posting questions and advice let me know.

    Basically I've been following a tutorial for a while now and while I've learned a lot, something about the code isn't compatible with the addition of a jump buffer and coyote timer. I've tried a few different methods and even references to codes that seem similar in implementation are working. I'm not sure if it has something to do with ground snapping or how I have jump phases defined but I've been stumped for a few days now. Anything to help steer me in the right direction would be greatly appreciated. The person who made the tutorial has some life stuff going on and hasn’t gotten back to me, so I’m posting here.

    The code is below. I've attempted to purge some lines of code that I don't think would pertain to the issue. Cheers.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class SphereGame : MonoBehaviour {
    4.  
    5.     [SerializeField]
    6.     Transform playerInputSpace = default, ball = default;
    7.  
    8.     [SerializeField, Range(0f, 100f)]
    9.     float maxSpeed = 15f, maxClimbSpeed = 4f, maxSwimSpeed = 5f;
    10.  
    11.     [SerializeField, Range(0f, 100f)]
    12.     float
    13.         maxAcceleration = 67.5f,
    14.         maxAirAcceleration = 20f,
    15.         maxClimbAcceleration = 40f,
    16.         maxSwimAcceleration = 5f;
    17.  
    18.     [SerializeField, Range(0f, 10f)]
    19.     float jumpHeight = 2.35f;
    20.  
    21.     [SerializeField, Range(0, 5)]
    22.     int maxAirJumps = 1;
    23.  
    24.     [SerializeField, Range(0, 90)]
    25.     float maxGroundAngle = 15f, maxStairsAngle = 50f;
    26.  
    27.     [SerializeField, Range(90, 170)]
    28.     float maxClimbAngle = 140f;
    29.  
    30.     [SerializeField, Range(0f, 100f)]
    31.     float maxSnapSpeed = 100f;
    32.  
    33.     [SerializeField, Min(0f)]
    34.     float probeDistance = 1f;
    35.  
    36.     [SerializeField]
    37.     float submergenceOffset = 0.5f;
    38.  
    39.     [SerializeField, Min(0.1f)]
    40.     float submergenceRange = 1f;
    41.  
    42.     [SerializeField, Min(0f)]
    43.     float buoyancy = 1f;
    44.  
    45.     [SerializeField, Range(0f, 10f)]
    46.     float waterDrag = 1f;
    47.  
    48.     [SerializeField, Range(0.01f, 1f)]
    49.     float swimThreshold = 0.5f;
    50.  
    51.     [SerializeField]
    52.     LayerMask
    53.         probeMask = -1,
    54.         stairsMask = -1,
    55.         climbMask = -1,
    56.         waterMask = 0;
    57.  
    58.     [SerializeField]
    59.     Material
    60.         normalMaterial = default,
    61.         climbingMaterial = default,
    62.         swimmingMaterial = default;
    63.  
    64.     [SerializeField, Min(0.1f)]
    65.     float ballRadius = 0.5f;
    66.  
    67.     [SerializeField, Min(0f)]
    68.     float ballAlignSpeed = 180f;
    69.  
    70.     [SerializeField, Min(0f)]
    71.     float ballAirRotation = 0.5f, ballSwimRotation = 2f;
    72.  
    73.     //[SerializeField, Range(0f, 0.3f)]  float jumpBuffer = 0.15f;
    74.  
    75.     Rigidbody body, connectedBody, previousConnectedBody;
    76.  
    77.     Vector3 playerInput;
    78.  
    79.     Vector3 velocity, connectionVelocity;
    80.  
    81.     Vector3 connectionWorldPosition, connectionLocalPosition;
    82.  
    83.     Vector3 upAxis, rightAxis, forwardAxis;
    84.  
    85.     bool desiredJump, desiresClimbing;
    86.  
    87.     Vector3 contactNormal, steepNormal, climbNormal, lastClimbNormal;
    88.  
    89.     Vector3 lastContactNormal, lastSteepNormal, lastConnectionVelocity;
    90.  
    91.     int groundContactCount, steepContactCount, climbContactCount;
    92.  
    93.     bool OnGround => groundContactCount > 0;
    94.  
    95.     bool OnSteep => steepContactCount > 0;
    96.  
    97.     bool Climbing => climbContactCount > 0 && stepsSinceLastJump > 2;
    98.  
    99.     bool InWater => submergence > 0f;
    100.  
    101.     bool Swimming => submergence >= swimThreshold;
    102.  
    103.     float submergence;
    104.  
    105.     int jumpPhase;
    106.  
    107.     float minGroundDotProduct, minStairsDotProduct, minClimbDotProduct;
    108.  
    109.     int stepsSinceLastGrounded, stepsSinceLastJump;
    110.  
    111.     MeshRenderer meshRenderer;
    112.  
    113.     // This prevents the ground snapping from affecting your jump height.
    114.     public void PreventSnapToGround () {
    115.         stepsSinceLastJump = -1;
    116.     }
    117.  
    118.     void OnValidate () {
    119.         minGroundDotProduct = Mathf.Cos(maxGroundAngle * Mathf.Deg2Rad);
    120.         minStairsDotProduct = Mathf.Cos(maxStairsAngle * Mathf.Deg2Rad);
    121.         minClimbDotProduct = Mathf.Cos(maxClimbAngle * Mathf.Deg2Rad);
    122.     }
    123.  
    124.     void Awake () {
    125.         body = GetComponent<Rigidbody>();
    126.         body.useGravity = false;
    127.         meshRenderer = ball.GetComponent<MeshRenderer>();
    128.         OnValidate();
    129.     }
    130.  
    131.     void Update () {
    132.         // This is for player controls and accounts for being in water or alterations to gravity as well!
    133.         playerInput.x = Input.GetAxis("Horizontal");
    134.         playerInput.z = Input.GetAxis("Vertical");
    135.         playerInput.y = Swimming ? Input.GetAxis("UpDown") : 0f;
    136.         playerInput = Vector3.ClampMagnitude(playerInput, 1f);
    137.  
    138.         if (playerInputSpace) {
    139.             rightAxis = ProjectDirectionOnPlane(playerInputSpace.right, upAxis);
    140.             forwardAxis =
    141.                 ProjectDirectionOnPlane(playerInputSpace.forward, upAxis);
    142.         }
    143.         else {
    144.             rightAxis = ProjectDirectionOnPlane(Vector3.right, upAxis);
    145.             forwardAxis = ProjectDirectionOnPlane(Vector3.forward, upAxis);
    146.         }
    147.  
    148.         if (Swimming) {
    149.             desiresClimbing = false;
    150.         }
    151.         else {
    152.             desiredJump |= Input.GetButtonDown("Jump");
    153.             desiresClimbing = Input.GetButton("Climb");
    154.         }
    155.  
    156.         UpdateBall();
    157.     }
    158.  
    159.     void FixedUpdate () {
    160.         Vector3 gravity = CustomGravity.GetGravity(body.position, out upAxis);
    161.         UpdateState();
    162.  
    163.         if (InWater) {
    164.             velocity *= 1f - waterDrag * submergence * Time.deltaTime;
    165.         }
    166.  
    167.         AdjustVelocity();
    168.  
    169.         if (desiredJump) {
    170.             desiredJump = false;
    171.             Jump(gravity);
    172.         }
    173.         if (Climbing) {
    174.             velocity -=
    175.                 contactNormal * (maxClimbAcceleration * 0.9f * Time.deltaTime);
    176.         }
    177.         else if (InWater) {
    178.             velocity +=
    179.                 gravity * ((1f - buoyancy * submergence) * Time.deltaTime);
    180.         }
    181.         else if (OnGround && velocity.sqrMagnitude < 0.01f) {
    182.             velocity +=
    183.                 contactNormal *
    184.                 (Vector3.Dot(gravity, contactNormal) * Time.deltaTime);
    185.         }
    186.         else if (desiresClimbing && OnGround) {
    187.             velocity +=
    188.                 (gravity - contactNormal * (maxClimbAcceleration * 0.9f)) *
    189.                 Time.deltaTime;
    190.         }
    191.         else {
    192.             velocity += gravity * Time.deltaTime;
    193.         }
    194.         body.velocity = velocity;
    195.         ClearState();
    196.     }
    197.  
    198.     void ClearState () {
    199.         lastContactNormal = contactNormal;
    200.         lastSteepNormal = steepNormal;
    201.         lastConnectionVelocity = connectionVelocity;
    202.         groundContactCount = steepContactCount = climbContactCount = 0;
    203.         contactNormal = steepNormal = climbNormal = Vector3.zero;
    204.         connectionVelocity = Vector3.zero;
    205.         previousConnectedBody = connectedBody;
    206.         connectedBody = null;
    207.         submergence = 0f;
    208.     }
    209.  
    210.     void UpdateState () {
    211.         stepsSinceLastGrounded += 1;
    212.         stepsSinceLastJump += 1;
    213.         velocity = body.velocity;
    214.         if (
    215.             CheckClimbing() || CheckSwimming() ||
    216.             OnGround || SnapToGround() || CheckSteepContacts()
    217.         ) {
    218.             stepsSinceLastGrounded = 0;
    219.             if (stepsSinceLastJump > 1) {
    220.                 jumpPhase = 0;
    221.             }
    222.             if (groundContactCount > 1) {
    223.                 contactNormal.Normalize();
    224.             }
    225.         }
    226.         else {
    227.             contactNormal = upAxis;
    228.         }
    229.      
    230.         if (connectedBody) {
    231.             if (connectedBody.isKinematic || connectedBody.mass >= body.mass) {
    232.                 UpdateConnectionState();
    233.             }
    234.         }
    235.     }
    236.  
    237.     void UpdateConnectionState () {
    238.         if (connectedBody == previousConnectedBody) {
    239.             Vector3 connectionMovement =
    240.                 connectedBody.transform.TransformPoint(connectionLocalPosition) -
    241.                 connectionWorldPosition;
    242.             connectionVelocity = connectionMovement / Time.deltaTime;
    243.         }
    244.         connectionWorldPosition = body.position;
    245.         connectionLocalPosition = connectedBody.transform.InverseTransformPoint(
    246.             connectionWorldPosition
    247.         );
    248.     }
    249.  
    250.     bool SnapToGround () {
    251.         if (stepsSinceLastGrounded > 1 || stepsSinceLastJump <= 2 || InWater) {
    252.             return false;
    253.         }
    254.         float speed = velocity.magnitude;
    255.         if (speed > maxSnapSpeed) {
    256.             return false;
    257.         }
    258.         if (!Physics.Raycast(
    259.             body.position, -upAxis, out RaycastHit hit,
    260.             probeDistance, probeMask, QueryTriggerInteraction.Ignore
    261.         )) {
    262.             return false;
    263.         }
    264.  
    265.         float upDot = Vector3.Dot(upAxis, hit.normal);
    266.         if (upDot < GetMinDot(hit.collider.gameObject.layer)) {
    267.             return false;
    268.         }
    269.  
    270.         groundContactCount = 1;
    271.         contactNormal = hit.normal;
    272.         float dot = Vector3.Dot(velocity, hit.normal);
    273.         if (dot > 0f) {
    274.             velocity = (velocity - hit.normal * dot).normalized * speed;
    275.         }
    276.         connectedBody = hit.rigidbody;
    277.         return true;
    278.     }
    279.  
    280.     bool CheckSteepContacts () {
    281.         if (steepContactCount > 1) {
    282.             steepNormal.Normalize();
    283.             float upDot = Vector3.Dot(upAxis, steepNormal);
    284.             if (upDot >= minGroundDotProduct) {
    285.                 steepContactCount = 0;
    286.                 groundContactCount = 1;
    287.                 contactNormal = steepNormal;
    288.                 return true;
    289.             }
    290.         }
    291.         return false;
    292.     }
    293.  
    294.     void AdjustVelocity () {
    295.         float acceleration, speed;
    296.         Vector3 xAxis, zAxis;
    297.         if (Climbing) {
    298.             acceleration = maxClimbAcceleration;
    299.             speed = maxClimbSpeed;
    300.             xAxis = Vector3.Cross(contactNormal, upAxis);
    301.             zAxis = upAxis;
    302.         }
    303.         else if (InWater) {
    304.             float swimFactor = Mathf.Min(1f, submergence / swimThreshold);
    305.             acceleration = Mathf.LerpUnclamped(
    306.                 OnGround ? maxAcceleration : maxAirAcceleration,
    307.                 maxSwimAcceleration, swimFactor
    308.             );
    309.             speed = Mathf.LerpUnclamped(maxSpeed, maxSwimSpeed, swimFactor);
    310.             xAxis = rightAxis;
    311.             zAxis = forwardAxis;
    312.         }
    313.         else {
    314.             acceleration = OnGround ? maxAcceleration : maxAirAcceleration;
    315.             speed = OnGround && desiresClimbing ? maxClimbSpeed : maxSpeed;
    316.             xAxis = rightAxis;
    317.             zAxis = forwardAxis;
    318.         }
    319.         xAxis = ProjectDirectionOnPlane(xAxis, contactNormal);
    320.         zAxis = ProjectDirectionOnPlane(zAxis, contactNormal);
    321.  
    322.         Vector3 relativeVelocity = velocity - connectionVelocity;
    323.  
    324.         Vector3 adjustment;
    325.         adjustment.x =
    326.             playerInput.x * speed - Vector3.Dot(relativeVelocity, xAxis);
    327.         adjustment.z =
    328.             playerInput.z * speed - Vector3.Dot(relativeVelocity, zAxis);
    329.         adjustment.y = Swimming ?
    330.             playerInput.y * speed - Vector3.Dot(relativeVelocity, upAxis) : 0f;
    331.      
    332.         adjustment =
    333.             Vector3.ClampMagnitude(adjustment, acceleration * Time.deltaTime);
    334.  
    335.         velocity += xAxis * adjustment.x + zAxis * adjustment.z;
    336.         if (Swimming) {
    337.             velocity += upAxis * adjustment.y;
    338.         }
    339.     }
    340.  
    341.     void Jump (Vector3 gravity) {
    342.         Vector3 jumpDirection;
    343.         if (OnGround) {
    344.             jumpDirection = contactNormal;
    345.         }
    346.         else if (OnSteep) {
    347.             jumpDirection = steepNormal;
    348.             // This controls air jump recovery from wall jumps
    349.             jumpPhase = 0;
    350.         }
    351.         else if (maxAirJumps > 0 && jumpPhase <= maxAirJumps) {
    352.             // This controls how many jumps you get when leaving a surface without jumping.
    353.             if (jumpPhase == 0) {
    354.                 jumpPhase = 1;
    355.             }
    356.             jumpDirection = contactNormal;
    357.         }
    358.         else {
    359.             return;
    360.         }
    361.  
    362.         stepsSinceLastJump = 0;
    363.         jumpPhase += 1;
    364.         // This determines desired jump height while accounting for force needed to overcome gravity(??)
    365.         float jumpSpeed = Mathf.Sqrt(2f * gravity.magnitude * jumpHeight);
    366.         if (InWater) {
    367.             jumpSpeed *= Mathf.Max(0f, 1f - submergence / swimThreshold);
    368.         }
    369.         jumpDirection = (jumpDirection + upAxis).normalized;
    370.         float alignedSpeed = Vector3.Dot(velocity, jumpDirection);
    371.         // This prevents your jump from losing momentum if an upward force exceeds the jump force.
    372.         if (alignedSpeed > 0f) {
    373.             jumpSpeed = Mathf.Max(jumpSpeed - alignedSpeed, 0f);
    374.         }
    375.         // This prevents the double jump from not giving much height if you jump late into a fall.
    376.         else if (alignedSpeed < 0f) {
    377.             jumpSpeed -= alignedSpeed;
    378.         }
    379.      
    380.         velocity += jumpDirection * jumpSpeed;
    381.  
    382.     }
    383.  
    384.     void OnCollisionEnter (Collision collision) {
    385.         EvaluateCollision(collision);
    386.     }
    387.  
    388.     void OnCollisionStay (Collision collision) {
    389.         EvaluateCollision(collision);
    390.     }
    391.  
    392.     void EvaluateCollision (Collision collision) {
    393.         if (Swimming) {
    394.             return;
    395.         }
    396.         int layer = collision.gameObject.layer;
    397.         float minDot = GetMinDot(layer);
    398.         for (int i = 0; i < collision.contactCount; i++) {
    399.             Vector3 normal = collision.GetContact(i).normal;
    400.             float upDot = Vector3.Dot(upAxis, normal);
    401.             if (upDot >= minDot) {
    402.                 groundContactCount += 1;
    403.                 contactNormal += normal;
    404.                 connectedBody = collision.rigidbody;
    405.             }
    406.             else {
    407.                 if (upDot > -0.01f) {
    408.                     steepContactCount += 1;
    409.                     steepNormal += normal;
    410.                     if (groundContactCount == 0) {
    411.                         connectedBody = collision.rigidbody;
    412.                     }
    413.                 }
    414.                 if (
    415.                     desiresClimbing && upDot >= minClimbDotProduct &&
    416.                     (climbMask & (1 << layer)) != 0
    417.                 ) {
    418.                     climbContactCount += 1;
    419.                     climbNormal += normal;
    420.                     lastClimbNormal = normal;
    421.                     connectedBody = collision.rigidbody;
    422.                 }
    423.             }
    424.         }
    425.     }
    426.  
    427.     Vector3 ProjectDirectionOnPlane (Vector3 direction, Vector3 normal) {
    428.         return (direction - normal * Vector3.Dot(direction, normal)).normalized;
    429.     }
    430.  
    431.     float GetMinDot (int layer) {
    432.         return (stairsMask & (1 << layer)) == 0 ?
    433.             minGroundDotProduct : minStairsDotProduct;
    434.     }
    435. }
    436.  
     
    Last edited: May 19, 2023
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    You're welcome to take mine here if you like... it's in my proximity_buttons public repo:



    proximity_buttons is presently hosted at these locations:

    https://bitbucket.org/kurtdekker/proximity_buttons

    https://github.com/kurtdekker/proximity_buttons

    https://gitlab.com/kurtdekker/proximity_buttons

    https://sourceforge.net/projects/proximity-buttons/

    Otherwise, here's how to begin debugging your code:

    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.