- Home /
How to switch between animations based upon the location of joystick?
How can I switch between the Idle, Walk, and Run animations based upon the location of the joystick? If the joystick is at the center, the Idle animation will play. If the joystick is halfway between the max radius of the pad, the Walk animation will play. If the joystick is all the way at the max radius of the pad, the Run animation will play.
Here is my Player script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Player : MonoBehaviour
{
Vector3 moveInputOfLeftJoystick;
Vector3 moveInputOfRightJoystick;
public Joystick leftJoystick;
public Joystick rightJoystick;
NavMeshAgent agent;
Animator animator;
public GameOver gameOver;
public float movementSpeed;
public GameObject bulletSpawnPoint;
public float timeBetweenShots;
public GameObject bullet;
float shotCounter;
public float points;
public float maxHealth;
public float health;
void Start()
{
agent = GetComponent<NavMeshAgent>();
animator = GetComponentInChildren<Animator>();
health = maxHealth;
}
void Update()
{
shotCounter += Time.deltaTime;
//Player Movement
moveInputOfLeftJoystick = new Vector3(leftJoystick.Horizontal, 0f, leftJoystick.Vertical);
if (moveInputOfLeftJoystick != Vector3.zero)
{
transform.Translate(moveInputOfLeftJoystick * movementSpeed * Time.deltaTime, Space.World);
float speedPercent = agent.velocity.magnitude / agent.speed;
animator.SetFloat("speedPercent", speedPercent, .1f, Time.deltaTime);
}
//Player Rotation and Shooting
moveInputOfRightJoystick = new Vector3(rightJoystick.Horizontal, 0f, rightJoystick.Vertical);
if (moveInputOfRightJoystick != Vector3.zero)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(moveInputOfRightJoystick), 12 * Time.deltaTime);
if (shotCounter > timeBetweenShots)
{
Shoot();
shotCounter = 0;
}
}
if (health <= 0)
Die();
}
void Shoot()
{
Instantiate(bullet, bulletSpawnPoint.transform.position, bulletSpawnPoint.transform.rotation);
}
public void Die()
{
Destroy(this.gameObject);
gameOver.GameOverSetup();
}
}
Answer by TylerD14 · Aug 04, 2021 at 04:40 PM
The new Input system will do the job.
Input.GetAxis("Horizontal") will return a float value between -1 and 1. -1 is all the way left, 1 is all the way right, 0.5 is halfway right, etc
to change the joystick go to edit -> project settings -> Input -> Horizontal (the second one) and change the "axis" setting
I don't understand. Input.GetAxis("Horizontal") is from the old Input system.