Source Code Used in this Video
The following lines of code are to be placed on an already working script that moves the character left and right on the screen. For a working script, you can check out our other tutorial that explains how to do this by clicking here.
Put these two lines of code above your Start() function in the script that assigned to your character game object.
private Rigidbody2D rb2d;
private Animator animator;
Next inside your Start() function, define the references above so they are assigned to the character's correct components:
rb2d = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator> ();
Lastly, in your FixedUpdate() function, right after your function that moves your character, put these lines of code:
float characterSpeed = Mathf.Abs (rb2d.velocity.x);
animator.SetFloat ("Speed", characterSpeed);
What this does is assign characterSpeed to equal the characters velocity. Mathf.Abs is a built-in function that gives you a positive value of the float. So if the character is moving left on the screen the velocity will be a negative value, but we want to know how fast the character is moving in either direction so the value must always be positive. The next line of code assigns the parameter we setup in our Animator screen that we labeled "Speed" = to the velocity speed. We then use this value to manage the transition from idle to running in our animator.
A completed script would look something like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour {
//variables
public float moveSpeed = 50.0f;
private float ScreenWidth;
private Rigidbody2D rb2d;
private Animator animator;
// Use this for initialization
void Start () {
ScreenWidth = Screen.width;
rb2d = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator> ();
}
// Update is called once per frame
void Update () {
int i = 0;
//loop over every touch found
while (i < Input.touchCount) {
if (Input.GetTouch (i).position.x > ScreenWidth / 2) {
//move right
RunCharacter (1.0f);
}
if (Input.GetTouch (i).position.x < ScreenWidth / 2) {
//move left
RunCharacter (-1.0f);
}
++i;
}
}
void FixedUpdate(){
#if UNITY_EDITOR
RunCharacter(Input.GetAxis("Horizontal"));
#endif
float characterSpeed = Mathf.Abs (rb2d.velocity.x);
animator.SetFloat ("Speed", characterSpeed);
}
private void RunCharacter(float horizontalInput){
//move player
rb2d.AddForce(new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 0));
}
}