Search Unity

Can't get this running speed modifier code to work

Discussion in '2D' started by MasterElement, Jan 18, 2022.

  1. MasterElement

    MasterElement

    Joined:
    Jun 13, 2016
    Posts:
    140
    So I am working on a project that is a 2d platformer. I have been trying to fin a way to create a run instead of walk function, and I thought I found the perfect way using just a few simple lines of code and a float, that I found in a youtube tutorial. Thing is I tried it and it doesn't work, even though it does for the guy in the video, and I tried to duplicate his code several times. I was hoping you guys could take a look at this for me.
    Here is the video and what mark you can find the part about the code.

    Time 19:00 min.
    Here is my code
    Code (CSharp):
    1. public class ARCharacterController : MonoBehaviour
    2. {
    3.     //When using the function Translate it will not activate collisions as Velocity does.
    4.     // (Note) GetAxis function gives you numbers ranging from 1 to -1, GetAxisRaw will always give you a positive number.
    5.     //(Note) Any code followed by () at the end is a Method.
    6.     public float speed = 1;
    7.     // Private Fields
    8.     Rigidbody2D rb;
    9.     float horizontalValue;
    10.     bool facingRight = true;
    11.     bool isRunning = false;
    12.     float runSpeedModifier = 2f;
    13.  
    14.     // The Awake Function gets called as soon as the script is loaded into the scene, so the earliest point possible.
    15.     private void Awake()
    16.     {
    17.         rb = GetComponent<Rigidbody2D>();
    18.         //Sets the RigidBody value at game start.
    19.     }
    20.  
    21.     void Start()
    22.     {
    23.        
    24.     }
    25.  
    26.  
    27.     void Update()
    28.     {
    29.         horizontalValue = Input.GetAxisRaw("Horizontal");
    30.         //Checks Horizontal Value with each frame.
    31.        
    32.         // Flip Player
    33.         if(horizontalValue < 0 && facingRight)
    34.         {
    35.             flip();
    36.         }
    37.         else if (horizontalValue > 0 && !facingRight)
    38.         {
    39.             flip();
    40.         }
    41.  
    42.         if (Input.GetKeyDown(KeyCode.LeftShift))// Calls button press once
    43.         {
    44.             isRunning = true;
    45.            
    46.         }
    47.  
    48.         else if (Input.GetKeyUp(KeyCode.LeftShift))
    49.         {
    50.             isRunning = false;
    51.         }
    52.     }
    53.  
    54.     void FixedUpdate()
    55.     {
    56.         Move(horizontalValue);
    57.     }
    58.  
    59.     void Move(float dir)
    60.     {
    61.         float xVal = dir * speed * Time.deltaTime;
    62.         Vector2 targetVelocity = new Vector2(xVal,rb.velocity.y);
    63.         // In this Vector2 dir represents the X value why rb.velocity.y is the Y value. The second leaves the Y value the same when the code is run.
    64.  
    65.         rb.velocity = targetVelocity;
    66.  
    67.         //If running multiply speed with running modifier.
    68.         if(isRunning)
    69.         {
    70.             xVal *= runSpeedModifier;
    71.         }
    72.     }
    73.  
    74.     //Flip Player using rotation rather then changing the player's X scale from 1 to -1 and visa versa.
    75.     // WHen facingRight is true, turn left, and when facingRight is false turn right.
    76.     void flip()
    77.     {
    78.         facingRight = !facingRight; // when activated if facingRight is true, then it becomes false. And visa versa
    79.         transform.Rotate(0f, 180f, 0f);
    80.     }
    81. }
    So the line of code in question is
    Code (CSharp):
    1. if(isRunning)
    2.         {
    3.             xVal *= runSpeedModifier;
    4.         }
    I have bug tested it do it works up to that code then it does nothing.
    I tried an experiment be replacing
    xVal with the previous variable speed, which did increase the speed when left shift was pressed but it was all glitchy.
    I just can't figure out what it wrong, any ideas?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    Oh my goodness, don't stop there! Keep going!!

    You must find a way to get the information you need in order to reason about what the problem is.

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

    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
     
  3. MasterElement

    MasterElement

    Joined:
    Jun 13, 2016
    Posts:
    140
    Thanks but that is not really the help I was asking for. As I already said I used debug on the parts of the code that lead into the section of code in question and it all worked as it should have. Plus I substituted xVal float with the speed one and it worked as it should have only with the movement all messed up, but the speed did increase as it should have. I was hoping someone could take a look at it, as I have spent several hours on it and come up with nothing. And having someone else look often leads them to spotting things you kept missing.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    If you had put a Debug.Log() statement immediately before you use it on line 62 and then displayed what
    xVal
    both normally and when running, you would have INSTANTLY noticed that it didn't change.

    That would immediately draw your eye down to the line where you CHANGE it, line 68 to 71

    And then your eye would go up to the line where you USE xVal... line 62.

    And that would say to you, "Gosh, if I want something to be changed when I go to use it, I must change it BEFORE I use it, not 6 lines AFTER I use it."

    This is how debugging works. You have GOT to be able to do it or you are going to have a very rough time programming.

    :)
     
  5. MasterElement

    MasterElement

    Joined:
    Jun 13, 2016
    Posts:
    140
    You're right the guy in the tutorial placed it before Vector2 target velocity. I didn't because I thought it would be easier to follow formatting to do it after. It didn't occur to me that placement was important. But now I know.
    Thanks for your help.
     
    Kurt-Dekker likes this.