Search Unity

Bug Touch Controls not allowing me to move the character not really sure why

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

  1. blueorange27

    blueorange27

    Joined:
    Mar 8, 2018
    Posts:
    2
    I am trying to get on screen touch control to work for, all the button but the left and right arrows for the movement are working and I can't really understand where I went wrong with the logic, pretty new to Unity and this had been driving me mad z

    //Play Controller script
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.InputSystem;
    5.  
    6. public class PlayerMovement : MonoBehaviour
    7. {
    8.  
    9.     public ParticleSystem Dust;
    10.  
    11.  
    12.     //Animation States
    13.     const string IDLE_ANIMATION = "Idle_an";
    14.     const string JUMP_ANIMATION = "Jump_an";
    15.     const string RUN_ANIMATION = "Run_an";
    16.     const string PICKAXE_ATTACK_ANIMATION = "Pickaxe_an";
    17.     private float horizontal;
    18.     public float speed = 5f;
    19.     private float jumpingPower = 13f;
    20.     private bool isFacingRight = true;
    21.     private bool isJumpPressed;
    22.     private bool isAttacking;
    23.     private bool isAttackingPressed;
    24.  
    25.     public Transform attackHitBox;
    26.     public float attackRange = 0.5f;
    27.     public LayerMask enemyLayers;
    28.  
    29.     private float coyoteTime = 0.2f;
    30.      private float coyoteTimeCounter;
    31.  
    32.      private float jumpBufferTime = 0.2f;
    33.      private float jumpBufferCounter;
    34.  
    35.      public int damageToGive;
    36.  
    37.      [SerializeField] private Rigidbody2D rb;
    38.      [SerializeField] private Transform groundCheck;
    39.      [SerializeField] private LayerMask groundLayer;
    40.      [SerializeField] private float attackDelay = 1f;
    41.      Animator animator;
    42.      private string currentState;
    43.      void Start()
    44.      {
    45.         animator = GetComponent<Animator>();
    46.      }
    47.  
    48.  
    49.     // So I can make the Rigidbody acccessible to othe scripts
    50.     //While keeping the main one private with the player controller
    51.      public Rigidbody2D PlayerRigidbody
    52.     {
    53.     get { return rb; }
    54.     set { rb = value; }
    55.     }
    56.  
    57.    
    58.    
    59.  
    60.  
    61.  
    62.     void Update()
    63.     {
    64.         Move(Input.GetAxisRaw("Horizontal"));
    65.         /*Returns a raw value of the axis input. Which means it will return either -1,0 or 1 Depending on the direction of the input
    66.         -1 = (left,down), 1 = (right,up) 0 = there is no input*/
    67.         //horizontal = Input.GetAxisRaw("Horizontal");
    68.         //This allows a brief window which allows the player to jump even though they are not touching the ground
    69.         //Just like coyote not falling straight away when he runs off the edge in roadrunner.
    70.  
    71.         if(isGrounded())
    72.         {
    73.             coyoteTimeCounter = coyoteTime;
    74.  
    75.         }else
    76.         {
    77.             coyoteTimeCounter -= Time.deltaTime;
    78.  
    79.         }
    80.         //Allows the player buffer a jump while they are in the air, strictly a game feel thing.
    81.        
    82.         if(Input.GetButtonDown("Jump"))
    83.         {
    84.             jumpBufferCounter = jumpBufferTime;
    85.  
    86.         }else
    87.         {
    88.             jumpBufferCounter -= Time.deltaTime;
    89.  
    90.         }
    91.  
    92.  
    93.  
    94.         if(jumpBufferCounter > 0f && coyoteTimeCounter > 0f)
    95.         {
    96.             isJumpPressed = true;
    97.             rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
    98.  
    99.             jumpBufferCounter = 0f;
    100.         }
    101.  
    102.         if(Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
    103.         {
    104.             rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
    105.             coyoteTimeCounter = 0f;
    106.  
    107.         }
    108.  
    109.        
    110.          
    111.         Flip();
    112.  
    113.         //if(Input.GetMouseButtonDown(0))
    114.         //{
    115.         // PickAxe();
    116.        // }
    117.        
    118.     }
    119.  
    120.     public void Jump()
    121.     {
    122.         if(isGrounded())
    123.         {
    124.              isJumpPressed = true;
    125.              rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
    126.         }
    127.  
    128.     }
    129.  
    130.      public void Move(float moveInput)
    131.     {
    132.          horizontal = moveInput;
    133.     }
    134.     /*Fixed update is a method used in Unity used for physics calculations.
    135.     Its a special function that runs a fixed number of times per second.
    136.     Itis designed to update the position, velocity and other physical properties*/
    137.     private void FixedUpdate()
    138.     {
    139.         /*Overall, this code is setting the velocity of a Rigidbody2D component based on the horizontal input (stored in the "horizontal" variable)
    140.         and a speed value (stored in the "speed" variable).
    141.         This can be used to move the object left and right in response to user input*/
    142.         rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
    143.  
    144.         //This is for the change in animation, I don't want this to overriding, things like the jump animation so we check if we are grounded first
    145.         if(isGrounded() && !isAttacking){
    146.             if(horizontal != 0f)
    147.             {
    148.                 ChangeAnimationState(RUN_ANIMATION);
    149.                 CreateDust();
    150.  
    151.             }
    152.             else if(horizontal == 0)
    153.             {  
    154.             ChangeAnimationState(IDLE_ANIMATION);
    155.             }
    156.    
    157.         }
    158.  
    159.         if(isJumpPressed = true && !isGrounded() && !isAttacking){
    160.            
    161.             ChangeAnimationState(JUMP_ANIMATION);
    162.         }
    163.  
    164.         if(isAttackingPressed)
    165.         {
    166.             isAttackingPressed = false;
    167.  
    168.             if(!isAttacking)
    169.             {
    170.                 isAttacking = true;
    171.                 Attack();
    172.  
    173.             }
    174.             Invoke("AttackComplete", attackDelay);
    175.  
    176.         }
    177.        
    178.  
    179.        
    180.  
    181.     }
    182.  
    183.  
    184.  
    185.     public void PickAxe()
    186.     {
    187.         isAttackingPressed = true;
    188.     }
    189.  
    190.  
    191.  
    192.  
    193.  
    194.     void Attack()
    195.     {
    196.         ChangeAnimationState(PICKAXE_ATTACK_ANIMATION);
    197.         Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackHitBox.position, attackRange, enemyLayers);
    198.  
    199.         foreach(Collider2D enemy in hitEnemies)
    200.         {
    201.             Debug.Log("we hit" + enemy.name);
    202.             enemy.GetComponent<EnemyHealthManager>().giveDamage(damageToGive);
    203.            
    204.         }
    205.  
    206.  
    207.     }
    208.  
    209.     void OnDrawGizmosSelected()
    210.     {
    211.         if (attackHitBox == null)
    212.             return;
    213.  
    214.         Gizmos.DrawWireSphere(attackHitBox.position, attackRange);
    215.     }
    216.  
    217.     void AttackComplete()
    218.     {
    219.         isAttacking = false;
    220.  
    221.         if (isGrounded())
    222.     {
    223.         if (horizontal != 0f)
    224.         {
    225.             ChangeAnimationState(RUN_ANIMATION);
    226.             CreateDust();
    227.         }
    228.         else
    229.         {
    230.             ChangeAnimationState(IDLE_ANIMATION);
    231.         }
    232.     }
    233.     else
    234.     {
    235.         ChangeAnimationState(JUMP_ANIMATION);
    236.     }
    237.     }
    238.  
    239.     private bool isGrounded()
    240.     {  
    241.         /*Checks if the gameObject is currently on the ground. Creates a small gameObject
    242.         slightly below the player*/
    243.         //The "0.2f" value is the radius of the circle.
    244.         //The "groundLayer" parameter is a layer mask that's used to filter out other objects that we don't want to check for collisions with.
    245.         //The "groundCheck" transform is an empty game object that's placed at the bottom of the game object's sprite.
    246.    
    247.         return Physics2D.OverlapCircle(groundCheck.position, 0.1f, groundLayer);
    248.  
    249.     }
    250.  
    251.     private void Flip()
    252.     {  
    253.         //If statement used to filp the player, checks what direction they are moving in
    254.         //flips the player on the x Axis depending on the direction
    255.         if(isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
    256.         {
    257.             isFacingRight = !isFacingRight;
    258.             Vector3 localScale = transform.localScale;
    259.             localScale.x *= -1f;
    260.             transform.localScale = localScale;
    261.         }
    262.  
    263.     }
    264.  
    265.     void ChangeAnimationState(string newState)
    266.     {
    267.         //stop the same animation from interrupting itself
    268.         if (currentState == newState) return;
    269.        
    270.         //play the animation
    271.         animator.Play(newState);
    272.  
    273.         currentState = newState;
    274.  
    275.     }
    276.  
    277.     void CreateDust()
    278.     {
    279.         Dust.Play();
    280.  
    281.     }
    282. }
    283.  
    //Touch Control scripts

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class TouchControls : MonoBehaviour
    6. {
    7.  
    8.     private PlayerMovement thePlayer;
    9.     // Start is called before the first frame update
    10.     void Start()
    11.     {
    12.         thePlayer = FindObjectOfType<PlayerMovement>();
    13.        
    14.     }
    15.  
    16.     public void LeftArrow()
    17.     {
    18.         thePlayer.Move(-1);
    19.     }
    20.  
    21.      public void RightArrow()
    22.     {
    23.         thePlayer.Move(1);
    24.  
    25.     }
    26.  
    27.     public void UnpressedArrow()
    28.     {
    29.         thePlayer.Move(0);
    30.  
    31.     }
    32.  
    33.     public void PickAxe_Attack()
    34.     {
    35.         thePlayer.PickAxe();
    36.  
    37.     }
    38.  
    39.     public void JumpButton()
    40.     {
    41.         thePlayer.Jump();
    42.  
    43.     }
     
  2. blueorange27

    blueorange27

    Joined:
    Mar 8, 2018
    Posts:
    2
    Fix it I put it in to the start() instead and it worked
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,726
    Fix your errors first. Until all errors are fixed, all results are irrelevant.

    How to fix a NullReferenceException error

    https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

    Three steps to success:
    - Identify what is null <-- any other action taken before this step is WASTED TIME
    - Identify why it is null
    - Fix that

    After that, which should take only minutes, if you still have a problem them it is...

    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.