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

Anyone willing to QA my Player Controller Script?

Discussion in 'Scripting' started by Flapman, Jun 15, 2021.

  1. Flapman

    Flapman

    Joined:
    Aug 15, 2010
    Posts:
    84
    Hello all,

    I have been working on my personal project for the Unity Training: Create with Code. I followed just about everything I could in the series and still cannot make my movement and animations work that they should. I am sure there is something I am missing. I am hoping that someone on here would be willing to look at my project and give me some good insight and critique/help. It is meant to be a 2.5D Game.

    Objectives:

    Make my player (a cat) move along the X axis.
    When pressing the Left or Right Arrows (or WASD keys), move in that direction. The longer I press the key, the faster she moves, changing the animation from idle to walk to run.
    Jump is handled with the Space Bar. Jump animation happens from the "Any State."
    When selecting the opposite key (Left if currently pressing the right) the player changes direction and moves in the opposite direction on X. The same happens when next pressing the opposite key again.

    WHAT IS HAPPENING

    Player moves along X axis. Turning works but animations are not playing correctly and freeze up. Sometimes when changing direction, player keeps moving in the original direction but in reverse. Jump animation is not playing in any state.

    I tried to drive the animations based on Velocity and that only partly works. The full code is below.

    Note: I am still learning coding although... I know a lot more than I knew years ago. It has always been the "scary dark water" I have tried to avoid for years. But, as a one-person "indie" dev, I figured I better start learning this part of the game development process. :)

    Below is a quick video showing some of the problems and I have also attached 3 screenshots of the settings from 3 of the animations.



    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerController : MonoBehaviour
    6. {
    7.     //checklist:
    8.  
    9.     //Set directions and input amount
    10.     //moving left and right
    11.  
    12.     private float moveX;
    13.  
    14.     //make the player move
    15.  
    16.     private Rigidbody playerRb;
    17.  
    18.     //move parameters
    19.     private float jumpForce = 50.0f;
    20.     private float gravityModifier = 1.0f;
    21.     private float speedModifier = 15;
    22.     private bool isOnGround = true;
    23.     public GameObject projectilePrefab;
    24.  
    25.     //Set how fast our player can move
    26.     private float speed = 10.0f;
    27.  
    28.     //set turn speed
    29.     private float t_speed = 100.0f;
    30.     public float velocity = 10;
    31.  
    32.     //run animations
    33.  
    34.     public Animator playerAnim;
    35.  
    36.     //THE FOLLOWING WILL BE WORKED ON AFTER MOVEMENT AND MOVEMENT ANIMATION WORK CORRECTLY!!!!!
    37.  
    38.     // public ParticleSystem explosionParticle;
    39.     // public ParticleSystem dirtParticle;
    40.     //  AudioClip jumpSound;
    41.     // public AudioClip crashSound;
    42.     // private AudioSource playerAudio;
    43.  
    44.  
    45.     //public bool gameOver = false;
    46.  
    47.     // Start is called before the first frame update
    48.     void Start()
    49.     {
    50.         //get the Rigidbody Component
    51.         playerRb = GetComponent<Rigidbody>();
    52.         // playerAnim = GetComponent<Animator>(); // This is the basic animator
    53.         playerAnim = GetComponentInChildren<Animator>();
    54.         Physics.gravity *= gravityModifier;
    55.         // playerAudio = GetComponent<AudioSource>()
    56.  
    57.     }
    58.  
    59.     // Update is called once per frame
    60.     void Update()
    61.     {
    62.         MovePlayer();
    63.         PlayerContraints();
    64.         if (Input.GetKeyDown(KeyCode.Return))
    65.         {
    66.             //Launch a projectile from the player
    67.             Instantiate(projectilePrefab, transform.position, projectilePrefab.transform.rotation);
    68.         }
    69.     }
    70.  
    71.  
    72.  
    73.     // Moves player except while jumping
    74.     void MovePlayer()
    75.     {
    76.         moveX = Input.GetAxis("Horizontal");
    77.         velocity = (playerRb.velocity.magnitude) * 1;
    78.  
    79.  
    80.         if (Input.GetKey(KeyCode.LeftArrow) && isOnGround)
    81.         {
    82.             //Rotate the character about the Y axis 180 degrees then move on x axis in the negative direction
    83.             //if already moving in that direction
    84.             transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0, -90, 0), Time.deltaTime * t_speed);
    85.             //transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(Vector3.left), Time.deltaTime * t_speed);
    86.             //playerAnim.SetBool("TurnL", true);
    87.             playerRb.AddForce(Vector3.left * moveX * speed * speedModifier * Time.deltaTime, ForceMode.Impulse);
    88.             playerAnim.SetFloat("Speed", velocity);
    89.  
    90.             //need to add turn animation when reversing direction
    91.  
    92.         }
    93.  
    94.         if (Input.GetKey(KeyCode.RightArrow) && isOnGround)
    95.         {
    96.             //Rotate the character about the Y axis 180 degrees then move on x axis in the positive direction
    97.             //if already moving in that direction
    98.        
    99.            transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0, 90, 0), Time.deltaTime * t_speed);
    100.             //playerAnim.SetBool("TurnR", true);
    101.             //transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(Vector3.right), Time.deltaTime * t_speed);
    102.             playerRb.AddForce(Vector3.right * moveX * speed * speedModifier * Time.deltaTime, ForceMode.Impulse);
    103.             playerAnim.SetFloat("Speed", velocity);
    104.  
    105.             //need to add turn animation when reversing direction
    106.  
    107.         }
    108.  
    109.         //If we want to be more 3D
    110.         //playerRb.AddForce(Vector3.forward * speed * speedModifier * verticalInput);
    111.     }
    112.  
    113.     // Detects Collisions
    114.     void OnCollisionEnter(Collision collision)
    115.     {
    116.         if (collision.gameObject.CompareTag("Ground"))
    117.         {
    118.             isOnGround = true;
    119.         }
    120.         if (collision.gameObject.CompareTag("Enemy"))
    121.         {
    122.             Debug.Log("Player has collided with enemy.");
    123.         }
    124.     }
    125.  
    126.     // Constrains player movement
    127.     //this is not working
    128.     void PlayerContraints()
    129.     {
    130.         if (Input.GetKeyDown(KeyCode.Space) && isOnGround)
    131.         {
    132.             playerRb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
    133.             isOnGround = false;
    134.             playerAnim.SetBool("Jump", true);
    135.         }
    136.         else
    137.         {
    138.             playerAnim.SetBool("Jump", false);
    139.         }
    140.     }
    141.  
    142.  
    143.  
    144.     //Detect Powerup Collisions
    145.     private void OnTriggerEnter(Collider other)
    146.     {
    147.         if(other.gameObject.CompareTag("Powerup"))
    148.         {
    149.             Destroy(other.gameObject);
    150.             StartCoroutine(PowerupCountdownRoutine());
    151.             Debug.Log("Player has captured a powerup.");
    152.         }
    153.         if(other.gameObject.CompareTag("Mouse"))
    154.         {
    155.             Destroy(other.gameObject);
    156.             StartCoroutine(PowerupCountdownRoutine());
    157.             Debug.Log("Player has captured a mouse.");
    158.         }
    159.     }
    160.  
    161.     //Start Delays
    162.     IEnumerator PowerupCountdownRoutine()
    163.     {
    164.         yield return new WaitForSeconds(7);
    165.         //hasPowerup = false;
    166.         //powerupIndicator.gameObject.SetActive(false);
    167.     }
    168.  
    169. }
    170.  
    171.  
     

    Attached Files:

  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,713
    Welcome to the dark scary water! It's great stuff! Best news is, the more you do dark scary water programming, the more you enjoy it and realize that you can do it too.

    For the particular issue above, it looks like you're already using some Debug.Log() statements, so that's GOOD.

    Now go nuts with them: 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 values of the variables involved? Are they initialized? Are the values reasonable?

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

    You can also put in Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene

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

    If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

    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
     
    Bunny83 likes this.
  3. Flapman

    Flapman

    Joined:
    Aug 15, 2010
    Posts:
    84
    Thanks for the guidance. I will start experimenting with the Debug.Log() statements in each section. I am sure a year from now I will look back and say, "I can't believe I was struggling with all of that...."

     
    Kurt-Dekker likes this.
  4. seejayjames

    seejayjames

    Joined:
    Jan 28, 2013
    Posts:
    685
    Also, if you need to monitor values that are updated often (like every frame), do them on-screen with a Text object. Much less overhead than printing to the Console, and you can read them more easily.
     
    Flapman likes this.
  5. Flapman

    Flapman

    Joined:
    Aug 15, 2010
    Posts:
    84
    Thanks for that suggestion. :)

     
    seejayjames likes this.