- Home /
Animations Through Scripting Probelm
I am making a script that allows me to walk and turn and when I do this, it will trigger an animation if the player doesn't walk it won't trigger the animation, it checks if the player walks or turns in the if statement that checks if xMove or yMove doesn't equal to 0. this is my code: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerController : MonoBehaviour
{
public Animator animator;
Rigidbody rb;
public float speed;
public float rotateSpeed = 20;
// Use this for initialization
void Start()
{
rb = this.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float xMove = Input.GetAxisRaw("Vertical");
float yMove = Input.GetAxisRaw("Horizontal");
if (xMove != 0)
{
transform.Translate((Vector3.forward) * xMove * speed);
animator.SetBool("IsRunning", true);
}
else
{
animator.SetBool("IsRunning", false);
}
if (yMove != 0)
{
transform.Rotate(0 , rotateSpeed * yMove , 0);
animator.SetBool("IsRunning", true);
}
else
{
animator.SetBool("IsRunning", false);
}
}
}
Answer by niiicolai · Aug 08, 2018 at 09:57 PM
You could setup a float parameter in your animator called speed
and then create a transition condition from your idle state to the walking state saying that if speed is greater than 0
it should pass and from the walking state to the idle state it only pass if speed is less than 0.1
.
Then you can update it like this in your code.
void Update() {
float xMove = Input.GetAxisRaw("Vertical");
float yMove = Input.GetAxisRaw("Horizontal");
if (xMove != 0) {
transform.Translate((Vector3.forward) * xMove * speed);
}
if (yMove != 0) {
transform.Rotate(0, rotateSpeed * yMove, 0);
}
// Since our condition is that if speed is greater than 0, we need to ensure a positive speed value.
xMove = (xMove < 0 ? -xMove : xMove);
yMove = (yMove < 0 ? -yMove : yMove);
// If xMove is zero we use yMove instead.
var currentSpeed = (xMove == 0 ? yMove : xMove);
// updates the animator with the new speed value every frame
animator.SetFloat("speed", currentSpeed);
}
Also you could use a blend tree. Take a look at https://docs.unity3d.com/Manual/class-BlendTree.html
Your answer
Follow this Question
Related Questions
Why does this extremely simple script return an error? 1 Answer
How do you make an object appear and disappear depending on position of player? 1 Answer
First script plays animation but second script stops if from playing said animation 1 Answer
Animating a Panel,Animating a panel 1 Answer
How can i impliment my animations (run to walk) in this script 0 Answers