Search Unity

Cannot jump like GetButtonDown with UI button

Discussion in 'Scripting' started by LerasQ, Aug 1, 2020.

  1. LerasQ

    LerasQ

    Joined:
    Jan 24, 2020
    Posts:
    3
    Hello, I'm making a 2D Endless runner and for now everything works fine with the jump (Regulable jump maded with custom character controller).

    But now I'm trying to do the same with a touchable UI button and I'm desperate. I'd try everything I know so far and I achieve that the button enable to jump but never like a GetButtonDown.

    It jumps the entire time that I hold the button, or it just jump each time I press the button or it jump only the small part of the "entire" jump when you hold the physical key.

    This is the Player.cs the main script and the other is the button script called JumpButton.cs :




    Player.cs

    Code (CSharp):
    1. using System.Collections;
    2.     using System.Collections.Generic;
    3.     using UnityEngine;
    4.     using UnityEngine.UI;
    5.  
    6.     public class Player : MonoBehaviour
    7.     {
    8.         [Header("General properties")]
    9.         [Tooltip("If checked, the controls of the player are completely disabled.")]
    10.         public bool blockControls = false;
    11.  
    12.         [Header("Eddless Runner.")]
    13.         [Tooltip("Makes the character move automatically.")]
    14.         public bool automaticMove = false;
    15.         [Range(-7.1f,7.1f)]
    16.         [Tooltip("Positive values go right and negative go left.")]
    17.         public float automaticSpeed = 0f;
    18.  
    19.         [Header("Horizontal Movement.")]
    20.         [Tooltip("The amount of normal speed. Don't worry if you reach the max speed set below.")]
    21.         public float moveSpeed = 10f;
    22.         [HideInInspector]
    23.         public Vector2 direction;
    24.         private bool facingRight = true;
    25.  
    26.         [Header("Vertical Movement")]
    27.         [Tooltip("The amount of jumpSpeed. Gravity will affect the formula too.")]
    28.         public float jumpSpeed = 8f;
    29.         [Tooltip("The time window that you are allowed to pre-jump before the character touches the ground.")]
    30.         public float jumpDelay = 0.25f;
    31.         private float jumpTimer;
    32.  
    33.         [Header("Joystick support")]
    34.         public bool jumpPad = false;
    35.         public JumpButton jumpButton;
    36.  
    37.         [Header("Components.")]
    38.         [Tooltip("The rigidbody of the player. Normally it will be the main gameobject.")]
    39.         public Rigidbody2D rb;
    40.         [Tooltip("The animator is the Gameobject that has the animator in components, it will be the child of the character holder")]
    41.         public Animator anim;
    42.         [Tooltip("The chosen layer will be the ground for our character.")]
    43.         public LayerMask groundLayer;
    44.         [Tooltip("Will be the child of the main gameobject and the parent of the animator character.")]
    45.         public GameObject characterHolder;
    46.         [Tooltip("This game manager is unique only to the script GameController, used for interactions.")]
    47.         public GameController theGameManager;
    48.         //[Tooltip("A integration with the joystick pack of unity assets.")]
    49.         //public VariableJoystick variableJoystick;
    50.  
    51.         [Header("Physics")]
    52.         [Tooltip("It sets the max reachable speed for the character.")]
    53.         public float maxSpeed = 6f;
    54.         [Tooltip("It sets the amount of the character linearDrag.")]
    55.         public float linearDrag = 8f;
    56.         [Tooltip("It sets the gravity scale for the player.")]
    57.         public float gravity = 1;
    58.         [Tooltip("It is used in the fall formula for our character.")]
    59.         public float fallMultiplier = 6f;
    60.  
    61.         [Header("Collision")]
    62.         [Tooltip("If the raycast touches the ground, this will be true.")]
    63.         public bool onGround = false;
    64.         [Tooltip("This will be the raycast lenght, it is pointing to the negative y value.")]
    65.         public float GroundLenght = 1.1f;
    66.         [Tooltip("The offset for the double raycast. And we split it for the two legs of our character.")]
    67.         public Vector3 colliderOffset;
    68.         void Update()
    69.         {
    70.             bool wasGround = onGround;
    71.             onGround = Physics2D.Raycast(transform.position + colliderOffset, Vector2.down, GroundLenght, groundLayer) || Physics2D.Raycast(transform.position - colliderOffset, Vector2.down, GroundLenght, groundLayer);
    72.          
    73.             if (Input.GetButtonDown("Jump"))
    74.             {
    75.                 jumpTimer = Time.time + jumpDelay;
    76.             }
    77.             if (jumpButton.finallyJump)
    78.             {
    79.                 jumpTimer = Time.time + jumpDelay;
    80.             }
    81.  
    82.             direction = new Vector2(Input.GetAxisRaw("Horizontal")/* + variableJoystick.Horizontal*/, Input.GetAxisRaw("Vertical"));
    83.         }
    84.  
    85.         void FixedUpdate()
    86.         {
    87.             if (!blockControls)
    88.             {
    89.  
    90.                 if (!automaticMove)
    91.                 {
    92.                 moveCharacter(direction.x);
    93.                 }
    94.                 else if (automaticMove == true)
    95.                 {
    96.                     moveCharacter(automaticSpeed);
    97.                 }
    98.  
    99.                 if(jumpTimer > Time.time && onGround)
    100.                 {
    101.                     Jump();
    102.                 }
    103.  
    104.                 modifyPhysics();
    105.             }
    106.             else
    107.             {
    108.                 rb.gravityScale = 1;
    109.             }
    110.         }
    111.         void moveCharacter(float horizontal)
    112.         {
    113.             rb.AddForce(Vector2.right * horizontal * moveSpeed);
    114.  
    115.             anim.SetFloat("horizontal", Mathf.Abs(rb.velocity.x));
    116.             anim.SetFloat("vertical", rb.velocity.y);
    117.             if((horizontal > 0 && !facingRight) || (horizontal < 0 && facingRight))
    118.             {
    119.                 Flip();
    120.             }
    121.             if (Mathf.Abs(rb.velocity.x) > maxSpeed)
    122.             {
    123.                 rb.velocity = new Vector2(Mathf.Sign(rb.velocity.x) * maxSpeed, rb.velocity.y);
    124.             }
    125.         }
    126.         void Jump()
    127.         {
    128.             rb.velocity = new Vector2(rb.velocity.x, 0); //Stops vertical movement.
    129.             rb.AddForce(Vector2.up * jumpSpeed, ForceMode2D.Impulse);
    130.             jumpTimer = 0;
    131.             StartCoroutine(JumpSqueeze(1.2f, 0.8f, 0.1f));
    132.         }
    133.         private void modifyPhysics()
    134.         {
    135.             bool changeDirection = (direction.x > 0 && rb.velocity.x < 0) || (direction.x < 0 && rb.velocity.x > 0);
    136.          
    137.             if(onGround)
    138.             {
    139.                 if(Mathf.Abs(direction.x) < 0.4f || changeDirection)
    140.                 {
    141.                     rb.drag = linearDrag;
    142.                 }
    143.                 else
    144.                 {
    145.                     rb.drag = 0f;
    146.                 }
    147.  
    148.                 rb.gravityScale = 0;
    149.             }
    150.             else
    151.             {
    152.                 rb.gravityScale = gravity;
    153.                 rb.drag = linearDrag * 0.15f;
    154.  
    155.                 if(rb.velocity.y < 0)
    156.                 {
    157.                     rb.gravityScale = gravity * fallMultiplier;
    158.                 }
    159.                 else if(rb.velocity.y > 0 && !Input.GetButton("Jump"))
    160.                 {
    161.                     rb.gravityScale = gravity * (fallMultiplier / 2);
    162.                 }
    163.             }
    164.         }
    165.         private void Flip()
    166.         {
    167.             // Switch the way the player is labelled as facing.
    168.             facingRight = !facingRight;
    169.  
    170.             // Multiply the player's x local scale by -1.
    171.             Vector3 theScale = transform.localScale;
    172.             theScale.x *= -1;
    173.             transform.localScale = theScale;
    174.         }
    175.         IEnumerator JumpSqueeze(float xSqueeze, float ySqueeze, float seconds) {
    176.             Vector3 originalSize = Vector3.one;
    177.             Vector3 newSize = new Vector3(xSqueeze, ySqueeze, originalSize.z);
    178.             float t = 0f;
    179.             while (t <= 1.0) {
    180.                 t += Time.deltaTime / seconds;
    181.                 characterHolder.transform.localScale = Vector3.Lerp(originalSize, newSize, t);
    182.                 yield return null;
    183.             }
    184.             t = 0f;
    185.             while (t <= 1.0) {
    186.                 t += Time.deltaTime / seconds;
    187.                 characterHolder.transform.localScale = Vector3.Lerp(newSize, originalSize, t);
    188.                 yield return null;
    189.             }
    190.  
    191.         }
    192.         private void OnDrawGizmos()
    193.         {
    194.             Gizmos.color = Color.blue;
    195.             Gizmos.DrawLine(transform.position + colliderOffset, transform.position + colliderOffset + Vector3.down * GroundLenght);
    196.             Gizmos.DrawLine(transform.position - colliderOffset, transform.position - colliderOffset + Vector3.down * GroundLenght);
    197.         }
    198.         //This is only for the spikes.
    199.         void OnCollisionEnter2D(Collision2D other)
    200.         {
    201.             if(other.gameObject.tag == "Bar")
    202.             {
    203.                 theGameManager.WhenCharDies();
    204.             }
    205.         }
    206.         public void WhenDeath(bool dead)
    207.         {
    208.             blockControls = dead;
    209.         }
    210.     }
    JumpButton.cs

    Code (CSharp):
    1.     using System.Collections;
    2.     using System.Collections.Generic;
    3.     using UnityEngine;
    4.     using UnityEngine.UI;
    5.     using UnityEngine.EventSystems;
    6.  
    7.     public class JumpButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
    8.     {
    9.         public bool allowJump = false;
    10.         public float timerJump;
    11.         public float delayJump = .25f;
    12.         public Player player;
    13.         public bool finallyJump = false;
    14.         //Detect current clicks on the GameObject (the one with the script attached)
    15.         public void OnPointerDown(PointerEventData pointerEventData)
    16.         {
    17.             //Output the name of the GameObject that is being clicked
    18.             Debug.Log(name + "Game Object Click in Progress");
    19.             //yield return new WaitForEndOfFrame();
    20.             //if (timerJump > Time.time && player.onGround)
    21.             //{
    22.             allowJump = true;
    23.             //}
    24.         }
    25.  
    26.         //Detect if clicks are no longer registering
    27.         public void OnPointerUp(PointerEventData pointerEventData)
    28.         {
    29.             Debug.Log(name + "No longer being clicked");
    30.             allowJump = false;
    31.         }
    32.         void Update()
    33.         {
    34.             timerJump = Time.time + delayJump;
    35.             if (allowJump && timerJump > Time.time)
    36.             {
    37.                 finallyJump = true;
    38.             }
    39.             else
    40.             {
    41.                 finallyJump = false;
    42.             }
    43.         }
    44.     }
    Feel free to say anything, maybe I miss something or wathever, but I was trying this for a 2 days now and I want to finish it, have to be a way without modify so much the code of Player.cs

    Thanks in advance, appreciate the help.
     
  2. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    How about to setup a Button which is invisible in the middle of the screen?

    then Create 2 New Functions, not event handlers, and set them up, maybe that will work
     
    LerasQ likes this.
  3. LerasQ

    LerasQ

    Joined:
    Jan 24, 2020
    Posts:
    3
    Thanks for the quick response.

    Mmmh, I Guess I understand the point of that but I'm beginner in this, could you explain it more precisely? Not needed to do the code, just expand the explanation please, thanks in advance, appreciated!
     
  4. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    Hey there,

    of course, so lets say,
    you create a GameObject[empty] -> add Button Component, in 2D Scale, you scale it to the area where you want the user to tap.

    Now you need a public function which makes your character Jump and assign it to it