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. Dismiss Notice

The player jumps correctly when moving left but not when moving right

Discussion in 'Scripting' started by PedroZamp, Aug 12, 2020.

  1. PedroZamp

    PedroZamp

    Joined:
    May 22, 2020
    Posts:
    6
    My player should always do the following animation sequence: idle/run -> jump -> fall -> idle/run, but when he falls while moving to the right, the fall animation will remain even after he's touched the ground, fading out only when I stop his movement.
    I've already checked the state machine for my player as well as his script, but everything seems alright.

    Caspar_Bug.gif
    Player's bug.

    caspar_animator.png
    Player's state machine.
    Player's script:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. //Todas as informações do jogador se encontram aqui.
    6. public class Player : Character
    7. {
    8.     //Booleano que determina se o jogador pode pular novamente.
    9.     private bool resetjump = false;
    10.     //Booleano que determina se o jogador está no chão.
    11.     private bool grounded = false;
    12.     //Float para o tempo de espera do jogador após atirar.
    13.     private float nextFireTime = 0;
    14.  
    15.     //Float para o tempo de recarga da arma do jogador.
    16.     [SerializeField] private float gunCooldown;
    17.     //Float para a altura do pulo do jogador.
    18.     [SerializeField] private float jumpForce;
    19.  
    20.  
    21.  
    22.     //Função de inicialização do jogador:
    23.     protected override void Init()
    24.     {
    25.         //Obtém os comandos de inicialização da classe pai,
    26.         base.Init();
    27.         //Determina que o jogador está virado para a direita,
    28.         facingRight = true;
    29.         //Determina a altura do pulo,
    30.         jumpForce = 14f;
    31.         //A velocidade do movimento e
    32.         moveSpeed = 8f;
    33.         //O tempo de recarga da arma do jogador.
    34.         gunCooldown = 0.35f;
    35.     }
    36.  
    37.  
    38.  
    39.     //Aplica a função de inicialização no primeiro frame do jogo.
    40.     void Start()
    41.     {
    42.         Init();
    43.     }
    44.  
    45.  
    46.  
    47.     //Aguarda os comandos de tiro e movimento do jogador a cada frame.
    48.     void Update()
    49.     {
    50.         Shoot();
    51.         Movement();
    52.     }
    53.  
    54.  
    55.  
    56.     //Função de tiro do jogador:
    57.     public override void Shoot()
    58.     {
    59.         //Se chegar o tempo onde o jogador pode atirar novamente e
    60.         if (Time.time > nextFireTime)
    61.         {
    62.             //Se o botão de tiro for apertado,
    63.             if (Input.GetKeyDown(KeyCode.L))
    64.             {
    65.                 //Reproduz a animação de tiro do jogador,
    66.                 anim.SetTrigger("shoot");
    67.                 //Instancia a bala do jogador e
    68.                 Instantiate(shotPrefab, firePoint.position, firePoint.rotation);
    69.                 //Acrescenta o tempo de recarga da arma ao float de espera.
    70.                 nextFireTime = Time.time + gunCooldown;
    71.             }
    72.         }
    73.     }
    74.  
    75.  
    76.  
    77.     //Função de movimento do jogador:
    78.     void Movement()
    79.     {
    80.         //Obtém o registro horizontal do jogador, que vai de -1 a 1.
    81.         //Valor negativo = movimento para a esquerda.
    82.         //Valor positivo = movimento para a direita.
    83.         float move = Input.GetAxisRaw("Horizontal");
    84.         //Verifica se o jogador está no chão.
    85.         grounded = IsGrounded();
    86.  
    87.         //Se o registro for positivo e o jogador estiver virado à esquerda,
    88.         if (move > 0 && !facingRight)
    89.         {
    90.             //O jogador dá meia-volta.
    91.             Flip();
    92.         }//Se o registro for negativo e o jogador estiver virado à direita,
    93.         else if (move < 0 && facingRight)
    94.         {
    95.             //O jogador dá meia-volta.
    96.             Flip();
    97.         }
    98.  
    99.         //Se o botão de pulo for apertado e o jogador estiver no chão,
    100.         if (Input.GetKeyDown(KeyCode.W) && IsGrounded())
    101.         {
    102.             //Aplica no jogador a força vertical do pulo,
    103.             rb.velocity = new Vector2(rb.velocity.x, jumpForce);
    104.             //Inicia a corrotina de reabilitação de pulo e
    105.             StartCoroutine(resetJumpRoutine());
    106.             //Reproduz a animação de pulo do jogador.
    107.             anim.SetBool("jump", true);
    108.         }
    109.  
    110.         if (rb.velocity.y < 0)
    111.         {
    112.             anim.SetBool("fall", true);
    113.             anim.SetBool("jump", false);
    114.         }
    115.  
    116.        
    117.  
    118.         //
    119.         //tentar aplicar GetKeyUp com mudança na gravidade para mudar intensidade do pulo
    120.         //
    121.  
    122.         //Por fim, aplica no jogador a força horizontal do movimento e
    123.         rb.velocity = new Vector2(move * moveSpeed, rb.velocity.y);
    124.         //Se o valor do registro não for 0, reproduz a animação de corrida do jogador.
    125.         anim.SetFloat("speed", Mathf.Abs(move));
    126.     }
    127.  
    128.  
    129.  
    130.     //Função que verifica se o jogador está no chão:
    131.     bool IsGrounded()
    132.     {
    133.         //Desenha na cena uma linha de debug partindo do jogador até o chão e
    134.         Debug.DrawRay(transform.position, Vector2.down * 1.4f, Color.green);
    135.         //Gera uma linha de colisão invisível correspondente à linha de debug.
    136.         RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, 1.4f, 1 << 9);
    137.  
    138.         //Se a linha colidir com algo (implicando que o jogador pousou em algo sólido) e
    139.         if (hit.collider != null)
    140.         {
    141.             //Se atualmente o jogador não puder pular,
    142.             if (resetjump == false)
    143.             {
    144.                 //Para a reprodução da animação de pulo do jogador e
    145.                 anim.SetBool("fall", false);
    146.                 //Confirma que o jogador está no chão.
    147.                 return true;
    148.             }
    149.  
    150.         }//Senão, confirma que o jogador não está no chão.
    151.         return false;
    152.     }
    153.  
    154.  
    155.  
    156.     //Corrotina de reabilitação do pulo do jogador:
    157.     IEnumerator resetJumpRoutine()
    158.     {
    159.         //Reabilita o pulo do jogador,
    160.         resetjump = true;
    161.         //Espera um determinado tempo e
    162.         yield return new WaitForSeconds(0.1f);
    163.         //O desabilita novamente.
    164.         resetjump = false;
    165.     }
    166.  
    167.    
    168.  
    169.     private void OnCollisionEnter2D(Collision2D other)
    170.     {
    171.         Debug.Log("Trigger called");
    172.         if (other.gameObject.CompareTag("Moving Platform") && !IsGrounded())
    173.         {
    174.             grounded = true;
    175.             transform.parent = other.gameObject.transform;
    176.         }
    177.         if (other.gameObject.CompareTag("Enemy"))
    178.         {
    179.             anim.SetTrigger("damage");
    180.         }
    181.     }
    182.    
    183.  
    184.     private void OnCollisionExit2D(Collision2D other)
    185.     {
    186.         if (other.gameObject.CompareTag("Moving Platform"))
    187.         {
    188.             transform.parent = null;
    189.         }
    190.     }
    191.  
    192.  
    193.  
    194.  
    195.  
    196.  
    197.  
    198.     public override void TakeDamage()
    199.     {
    200.         //HP--;
    201.  
    202.     }
    203.  
    204.    
    205.    
    206.  
    207. }
    208.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    I speculate the problem is in your Flip() routine perhaps? I don't see that code included above...
     
  3. PedroZamp

    PedroZamp

    Joined:
    May 22, 2020
    Posts:
    6
    Ah yes, the Flip() function is from the Character class. Here it is:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. //Informações genéricas dos personagens presentes na gameplay do jogo:
    6. public abstract class Character : MonoBehaviour
    7. {
    8.     //Todo personagem possui pontos de vida,
    9.     [SerializeField] protected int HP;
    10.     //Velocidade de movimento,
    11.     [SerializeField] protected float moveSpeed;
    12.     //Um tipo de bala para atirar e
    13.     [SerializeField] protected GameObject shotPrefab;
    14.     //Um ponto de onde essa bala será atirada.
    15.     [SerializeField] protected Transform firePoint;
    16.  
    17.     //Também possui um gerenciador de animação,
    18.     protected Animator anim;
    19.     //Um corpo gravitacional e
    20.     protected Rigidbody2D rb;
    21.     //Um booleano que armazena a direção à qual está virado.
    22.     protected bool facingRight;
    23.  
    24.  
    25.  
    26.     //Função de inicialização do personagem:
    27.     protected virtual void Init()
    28.     {
    29.         //Instancia o gerenciador de animação e
    30.         anim = GetComponent<Animator>();
    31.         //O corpo gravitacional do personagem.
    32.         rb = GetComponent<Rigidbody2D>();
    33.     }
    34.  
    35.  
    36.  
    37.     //Função de reorientação do personagem:
    38.     protected void Flip()
    39.     {
    40.         //Dá ao booleano a direção oposta à anterior e
    41.         facingRight = !facingRight;
    42.         //Vira o personagem horizontalmente em 180° graus.
    43.         transform.Rotate(0f, 180f, 0f);
    44.     }
    45.  
    46.    
    47.  
    48.     //Os personagens possuem funções de atirar e
    49.     public abstract void Shoot();
    50.     //Receber dano diferentes entre si,
    51.     public abstract void TakeDamage();
    52.     //Então devem implementá-las separadamente.
    53.  
    54. }
    55.