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.

Question Pressing Shift to Run

Discussion in 'Animation' started by jarzu4, Aug 6, 2020.

  1. jarzu4

    jarzu4

    Joined:
    Aug 4, 2020
    Posts:
    1
    Hi! I'm brand new to coding. I've been watching a video tutorial to make a 2D rpg game and was able to make the player move. However, the video doesn't show how to make the character run. I wanted to make the player run after the Shift button has been pressed. I already have the running animation ready and the running tree set up, but I can't figure out the right code. I've searched on google and watched other videos, no help so far... This is the code I'm using right now to simply move. Your help would be greatly appreciated!

    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class PlayerMovement : MonoBehaviour {
    7.  
    8.     public float speed;
    9.     private Rigidbody2D myRigidbody;
    10.     private Vector3 change;
    11.     private Animator animator;
    12.    
    13.    
    14.     void Start() {
    15.         animator = GetComponent<Animator>();
    16.         myRigidbody = GetComponent<Rigidbody2D>();
    17.     }
    18.  
    19.  
    20.     // Update is called once per frame
    21.     void FixedUpdate() {
    22.         change = Vector3.zero;
    23.         change.x = Input.GetAxisRaw("Horizontal");
    24.         change.y = Input.GetAxisRaw("Vertical");
    25.         UpdateAnimationAndMove();
    26.     }
    27.  
    28. void UpdateAnimationAndMove()
    29. {
    30.     if (change != Vector3.zero)
    31.        {
    32.            MoveCharacter();
    33.            animator.SetFloat("moveX", change.x);
    34.            animator.SetFloat("moveY", change.y);
    35.            animator.SetBool("moving", true);
    36.        }else{
    37.            animator.SetBool("moving",false);
    38.        }
    39. }
    40.     void MoveCharacter ()
    41.     {
    42.         myRigidbody.MovePosition(
    43.             transform.position + change.normalized * speed * Time.deltaTime);
    44.     }
    45. }
    46.