Cannot convert type `UnityEngine.Vector2' expression to type`float'
Hello guys, i am a beginner in unity2d, im following a tutorial on youtube, but i came across an error on the argument 'moveDir' i get the message "Cannot convert type UnityEngine.Vector2' expression to type float'", please help me to solve this error, all i want is to make animation when the character moves.. THANK YOU
public int moveSpeed;
public int jumpheight;
private Animator _anim;
Rigidbody2D rb2d;
// Use this for initialization
void Start () {
rb2d = GetComponent<Rigidbody2D>();
_anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
Vector2 moveDir = new Vector2(Input.GetAxisRaw("Horizontal")* moveSpeed, rb2d.velocity.y);
_anim.SetFloat("Speed", moveDir);
rb2d.velocity = moveDir;
if (Input.GetAxisRaw("Horizontal") == 1)
{
transform.localScale = new Vector3(1, 1, 1);
}
else if (Input.GetAxisRaw("Horizontal") == -1)
{
transform.localScale = new Vector3(-1, 1, 1);
}
if (Input.GetKeyDown(KeyCode.Space))
{
rb2d.AddForce(new Vector2(0, jumpheight));
}
Answer by Nerull22 · Sep 02, 2016 at 02:51 PM
So moveDir is actually a Vector2. It can't implicitly convert to a float. "moveDir" actually has an x and a y. Both are floats, so it can't implicitly convert to a float because it doesn't know what you want, and it can't know, you need to specify. Based on the fact that you're using the "Horizontal" axis I'm assuming that the animation is tied to your x-axis movement. So try modifying the following two line:
_anim.SetFloat("Speed", moveDir);
and modify "moveDir" to:
_anim.SetFloat("Speed", moveDir.x);
This will tell the compiler that you want to use the x direction of the Vector2 that was made. You can later use the y-direction for jumping or falling. Or any kind of combination you want to come up with. :D
rb2d.velocity is a Vector2 too, so the second line is just fine as:
rb2d.velocity = moveDir;
Haha, true story. $$anonymous$$y bad. :D I'll edit the original post. Nice catch, thanks.
Your answer
Follow this Question
Related Questions
How can I make the charecter jump in my game with this script I have? 0 Answers
Float superior or inferior not working 1 Answer
,Attack and chase range issue 2 Answers
Most suitable way to make player move for an open world environment? 0 Answers
My float is always adding 1f to it even with no code telling it to 1 Answer