Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Bug Help on my coyote timing

Discussion in '2D' started by IkarusBR, May 17, 2023.

  1. IkarusBR

    IkarusBR

    Joined:
    May 12, 2023
    Posts:
    8
    I was making a 2D platformer prototype code. I tried to add coyote timing so many times on the code but it always caused many different bugs (i.e infinite jump window, triple jump, not being able to jump and etc.). So I've decided to make something else - now the code is a lot more complete, but even then I can't use coyote timing. Right now, my double jump is only working a few moments after the jump. What should I do?
    (Notes: if you have any overall hints on how to improve the code, I'm taking those no problem.)
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Runtime.InteropServices.ComTypes;
    4. using DG.Tweening;
    5. using Unity.PlasticSCM.Editor.WebApi;
    6. using UnityEditor;
    7.  
    8. public class movimento : MonoBehaviour
    9. {
    10.     #region Variáveis de controle
    11.  
    12.     private bool isJumping = false;
    13.     private bool isRunning = false;
    14.     private bool isDashing = false;
    15.     private bool isDashCooldown = false;
    16.     private bool isSprintDash = false;
    17.     private bool isFacingRight = true;
    18.     private int jumpCount = 0;  // variável de contagem de pulo
    19.     private const int maxJumpCount = 2; // número máximo de pulos
    20.     #endregion
    21.  
    22.     #region Variáveis de entrada
    23.     private bool jumpKeyPressed;
    24.     private bool runKeyPressed;
    25.     private bool dashKeyPressed;
    26.     private float horizontalAxis;
    27.     #endregion
    28.  
    29.     #region Componentes
    30.     [SerializeField] private Rigidbody2D rb;
    31.     [SerializeField] private TrailRenderer td;
    32.     [SerializeField] private Transform groundCheck;
    33.     [SerializeField] private LayerMask groundLayer;
    34.     [SerializeField] private Transform wallCheck;
    35.     [SerializeField] private LayerMask wallLayer;
    36.     #endregion
    37.  
    38.     #region Parâmetros ajustáveis
    39.     [SerializeField]
    40.     private float forçaDoPulo = 15f;
    41.     [SerializeField]
    42.     private float jumpForceDecreaseFactor = 0.5f; // fator de diminuição da força do pulo
    43.     [SerializeField]
    44.     private float gravidade = 60f;
    45.     [SerializeField]
    46.     private float velocidade = 12f;
    47.     [SerializeField]
    48.     private float velocidadeCorrida = 18f;
    49.     [SerializeField]
    50.     private float transicaoVelocidade = 10f;
    51.     [SerializeField]
    52.     private float dashSpeed = 20f;
    53.     [SerializeField]
    54.     private float dashDuration = 0.2f;
    55.     [SerializeField]
    56.     private float dashCooldown = 0.1f;
    57.     [SerializeField]
    58.     private float jumpBufferLength = 0.1f;
    59.     [SerializeField]
    60.     private float fallSpeedMultiplier = 2f;
    61.     [SerializeField]
    62.     private float defaultGravityScale = 5f;
    63.     #endregion
    64.  
    65.     #region Variáveis privadas
    66.     private float jumpBufferCount;
    67.     private Vector2 dashVelocity;
    68.     private float fallTime;
    69.     private bool isDashAvailable = true;
    70.     private float originalDashSpeed;
    71.     private bool isWallSliding;
    72.     [SerializeField] private float wallSlidingSpeed = 2f;
    73.     private bool isWallJumping;
    74.     private float wallJumpingDirection;
    75.     [SerializeField]
    76.     private float wallJumpingTime = 0.2f;
    77.     private float wallJumpingCounter;
    78.     [SerializeField]
    79.     private float wallJumpingDuration = 0.4f;
    80.     [SerializeField]
    81.     private Vector2 wallJumpingPower = new Vector2(8f, 16f);
    82.     private bool hasAirJumped = false;  // Se o personagem já pulou no ar
    83.     [SerializeField] private float coyoteJumpDelay = 0.2f;
    84.     private float coyoteTimer;
    85.     private float jumpTimer;
    86.     [SerializeField] private float jumpDelay = 0.25f;
    87.  
    88.     #endregion
    89.  
    90.     #region Unity Callbacks
    91.     private void Start()
    92.     {
    93.         if (!TryGetComponent<Rigidbody2D>(out rb))
    94.         {
    95.             Debug.LogError("Componente Rigidbody2D não encontrado!");
    96.             this.enabled = false;
    97.         }
    98.         if (!TryGetComponent<TrailRenderer>(out td))
    99.         {
    100.             Debug.LogError("Componente TrailRenderer não encontrado!");
    101.             this.enabled = false;
    102.         }
    103.         originalDashSpeed = dashSpeed;
    104.     }
    105.  
    106.     private void Update()
    107.     {
    108.         ReadInput();
    109.         HandleInput();
    110.         WallSlide();
    111.         WallJump();
    112.         if (!isWallJumping)
    113.         {
    114.             Flip();
    115.         }
    116.         if (isGrounded() || IsWalled())
    117.         {
    118.             coyoteTimer = Time.time + coyoteJumpDelay;
    119.             if (isJumping) // Se estava pulando e agora está no chão
    120.             {
    121.                 isJumping = false;
    122.                 jumpCount = 0; // Resetamos a contagem de pulos
    123.                 hasAirJumped = false; // Resetamos o pulo no ar
    124.             }
    125.         }
    126.         else
    127.         {
    128.             isJumping = true;
    129.         }
    130.     }
    131.  
    132.     private void OnCollisionEnter2D(Collision2D collision)
    133.     {
    134.         if (collision.gameObject.CompareTag("Chao"))
    135.         {
    136.             isJumping = false;
    137.             isDashAvailable = true;
    138.         }
    139.     }
    140.  
    141.     private void OnCollisionExit2D(Collision2D collision)
    142.     {
    143.         if (collision.gameObject.CompareTag("Chao"))
    144.         {
    145.             isJumping = true;
    146.         }
    147.     }
    148.     #endregion
    149.  
    150.     #region Leitura das Entradas
    151.     private void ReadInput()
    152.     {
    153.         jumpKeyPressed = Input.GetKeyDown(KeyCode.Space);
    154.         runKeyPressed = Input.GetKey(KeyCode.LeftShift); // Alterado para GetKey
    155.         dashKeyPressed = Input.GetKeyDown(KeyCode.X);
    156.         horizontalAxis = Input.GetAxis("Horizontal");
    157.     }
    158.     #endregion
    159.  
    160.     #region Lógica do jogador
    161.     private void HandleInput()
    162.     {
    163.         if (jumpKeyPressed)
    164.         {
    165.             jumpBufferCount = jumpBufferLength;
    166.         }
    167.  
    168.         jumpBufferCount -= Time.deltaTime;
    169.  
    170.         // Adicionamos a condição de que o jogador só pode pular se o tempo de coyote ainda não tiver passado
    171.         if ((jumpCount < maxJumpCount && jumpBufferCount >= 0) && coyoteTimer > Time.time)
    172.         {
    173.             Pulo();
    174.         }
    175.  
    176.  
    177.         if (runKeyPressed) // Corre quando a tecla está pressionada
    178.         {
    179.             isRunning = true;
    180.         }
    181.         else // Para de correr quando a tecla é solta
    182.         {
    183.             isRunning = false;
    184.         }
    185.  
    186.         if (!isDashing && dashKeyPressed)
    187.         {
    188.             if (!isJumping || (isJumping && isDashAvailable)) // Permite o dash se não estiver no ar ou se estiver no ar, mas o dash estiver disponível
    189.             {
    190.                 StartCoroutine(Dash(horizontalAxis));
    191.                 isDashAvailable = false; // Desativa o dash após ser executado
    192.             }
    193.         }
    194.     }
    195.  
    196.     private void Pulo()
    197.     {
    198.         // Se o jogador já fez o número máximo de pulos, retornamos
    199.         if (jumpCount >= maxJumpCount) return;
    200.  
    201.         rb.velocity = new Vector2(rb.velocity.x, 0f);
    202.         // A força do pulo diminui a cada pulo adicional
    203.         rb.AddForce(Vector2.up * forçaDoPulo * (1 - jumpForceDecreaseFactor * (jumpCount - 1)), ForceMode2D.Impulse);
    204.         isJumping = true;
    205.         jumpBufferCount = 0;
    206.         // Incrementamos a contagem de pulos
    207.         jumpCount++;
    208.     }
    209.     private IEnumerator Dash(float direction)
    210.     {
    211.         float usedDashSpeed = dashSpeed;
    212.         if (isRunning && !isSprintDash)
    213.         {
    214.             usedDashSpeed += ((velocidadeCorrida + velocidade) / 3);
    215.             isSprintDash = true;
    216.             Dash(horizontalAxis);
    217.             Camera.main.transform.DOComplete();
    218.             Camera.main.transform.DOShakePosition(.3f, 1.2f, 14, 90, false, true);
    219.         }
    220.         if (!isRunning)
    221.             Camera.main.transform.DOComplete();
    222.         Camera.main.transform.DOShakePosition(.2f, .5f, 14, 90, false, true);
    223.         isDashing = true;
    224.         isDashCooldown = true;
    225.  
    226.         rb.gravityScale = 0f;
    227.  
    228.         float dashDirection = 0f;
    229.  
    230.         if (direction < 0)
    231.             dashDirection = -1f;
    232.         else if (direction > 0)
    233.             dashDirection = 1f;
    234.         else
    235.             dashDirection = transform.localScale.x;
    236.  
    237.         dashVelocity = new Vector2(usedDashSpeed * dashDirection, 0f);
    238.         float endTime = Time.time + dashDuration;
    239.  
    240.         while (Time.time < endTime)
    241.         {
    242.             float t = (endTime - Time.time) / dashDuration;
    243.             rb.velocity = Vector2.Lerp(rb.velocity, dashVelocity, 1f - t);
    244.             yield return null;
    245.         }
    246.  
    247.         rb.gravityScale = defaultGravityScale;
    248.  
    249.         isDashing = false;
    250.         isSprintDash = false;
    251.         dashSpeed = originalDashSpeed;
    252.  
    253.         yield return new WaitForSeconds(dashCooldown);
    254.  
    255.         isDashCooldown = false;
    256.     }
    257.     #endregion
    258.  
    259.     #region Física
    260.     private void FixedUpdate()
    261.     {
    262.         float velocidadeAtual = isRunning ? velocidadeCorrida : velocidade;
    263.         Vector2 velocidadeHorizontal = new Vector2(horizontalAxis * velocidadeAtual, rb.velocity.y);
    264.  
    265.         if (isDashing)
    266.         {
    267.             velocidadeHorizontal = dashVelocity;
    268.         }
    269.  
    270.         rb.velocity = Vector2.Lerp(rb.velocity, velocidadeHorizontal, transicaoVelocidade * Time.fixedDeltaTime);
    271.         if (!isJumping)
    272.         {
    273.             fallTime += Time.deltaTime;
    274.             float fallSpeed = Mathf.Sqrt(fallTime) * fallSpeedMultiplier;
    275.             if (rb.velocity.y < -fallSpeed)
    276.             {
    277.                 rb.velocity = new Vector2(rb.velocity.x, -fallSpeed);
    278.             }
    279.         }
    280.         else
    281.         {
    282.             fallTime = 0;
    283.         }
    284.         ApplyGravity();
    285.     }
    286.  
    287.     private void ApplyGravity()
    288.     {
    289.         if (!isDashing)
    290.         {
    291.             // Aqui a gravidade é aplicada independente da direção vertical do personagem
    292.             rb.AddForce(new Vector2(0f, -gravidade), ForceMode2D.Force);
    293.         }
    294.     }
    295.     private void Flip()
    296.     {
    297.         if (!isFacingRight && horizontalAxis > 0f || isFacingRight && horizontalAxis < 0f)
    298.         {
    299.             isFacingRight = !isFacingRight;
    300.             Vector3 localscale = transform.localScale;
    301.             localscale.x *= -1f;
    302.             transform.localScale = localscale;
    303.         }
    304.     }
    305.  
    306.     private bool isGrounded()
    307.     {
    308.         return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
    309.     }
    310.     private bool IsWalled()
    311.     {
    312.         return Physics2D.OverlapCircle(wallCheck.position, 0.2f, wallLayer);
    313.     }
    314.     private void WallSlide()
    315.     {
    316.         if (IsWalled() && !isGrounded() && horizontalAxis != 0f)
    317.         {
    318.             isWallSliding = true;
    319.             rb.velocity = new Vector3(rb.velocity.x, Mathf.Clamp(rb.velocity.y, -wallSlidingSpeed, float.MaxValue));
    320.         }
    321.         else
    322.         {
    323.             isWallSliding = false;
    324.         }
    325.     }
    326.     private void WallJump()
    327.     {
    328.         if (isWallSliding)
    329.         {
    330.             isWallJumping = false;
    331.             wallJumpingDirection = -transform.localScale.x;
    332.             wallJumpingCounter = wallJumpingTime;
    333.             CancelInvoke(nameof(StopWallJumping));
    334.         }
    335.         else
    336.         {
    337.             wallJumpingCounter -= Time.deltaTime;
    338.         }
    339.         if (jumpKeyPressed && wallJumpingCounter > 0f)
    340.         {
    341.             isWallJumping = true;
    342.             jumpCount = 0;  // Resetamos a contagem de pulos após um wall jump
    343.             hasAirJumped = false; // Resetamos o pulo no ar após um wall jump
    344.             rb.velocity = new Vector2(wallJumpingDirection * wallJumpingPower.x, wallJumpingPower.y);
    345.             wallJumpingCounter = 0f;
    346.             if (transform.localScale.x != wallJumpingDirection)
    347.             {
    348.                 isFacingRight = !isFacingRight;
    349.                 Vector3 localScale = transform.localScale;
    350.                 localScale.x *= -1f;
    351.                 transform.localScale = localScale;
    352.             }
    353.             Invoke(nameof(StopWallJumping), wallJumpingDirection);
    354.         }
    355.     }
    356.     private void StopWallJumping()
    357.     {
    358.         isWallJumping = false;
    359.     }
    360.     #endregion
    361. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,519
    You should begin 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.

    -------------------------------

    If you prefer, you're welcome to look at my multi-jump coyote timing demo here:



    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/
     
  3. IkarusBR

    IkarusBR

    Joined:
    May 12, 2023
    Posts:
    8
    i'm so sorry it took me this long to answer, thank you though, what you said makes sense :)