How do I make my speed be positive in any direction?
Hi, I'm making a top down 2d game and I am trying to set up the animations for my game. I currently have a transition from my idle animation to my blend tree for walking. The parameter I am using is speed. It is so when the speed is above 0 it goes to the tree and when it is less than .2 it goes back to the idle state. The problem is when I walk up the speed goes to one, but when I walk down it goes to -1 and when i go left and right it says at 0. Any help?
Here's my code
using UnityEngine;
using System.Collections;
public class topdown : MonoBehaviour
{
public float moveSpeed;
private Animator anim;
public float speed;
// Use this for initialization
void Start()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (Input.GetAxisRaw("Horizontal") > 0.5f || Input.GetAxisRaw("Horizontal") < 0.5f)
{
transform.Translate(new Vector3(Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime, 0f, 0f));
}
if (Input.GetAxisRaw("Vertical") > 0.5f || Input.GetAxisRaw("Vertical") < 0.5f)
{
transform.Translate(new Vector3(0f, Input.GetAxisRaw("Vertical") * moveSpeed * Time.deltaTime, 0f));
}
anim.SetFloat("speed", Input.GetAxisRaw("Horizontal"));
anim.SetFloat("speed", Input.GetAxisRaw("Vertical"));
}
}
Answer by Dave29483 · Feb 14, 2017 at 08:32 AM
float velocity = Mathf.Abs(new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")).magnitude);
anim.SetFloat("speed", velocity);
The idea is to create a 2D vector from the Input axes and get the magnitude/length. You then use Abs(); to flip the negative sign to positive.
How would /where would I add that in i added a float at the top named velocity and then added the thing you sent. but nothing happened. I also added a velocity parameter in the animator and that did nothing also.
Your answer
![](https://koobas.hobune.stream/wayback/20220612111040im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I find the direction I'm going for my blend tree? 0 Answers
Animations Bad Scripting | Controller Script Buggy | Collider Problem | Beginner Here! 0 Answers
Interchangeable animations in a script? 0 Answers
How do I make a x move and y move parameter 0 Answers
How can i make my enemy zombie do an animation when attacking and when he first sees the player 0 Answers