I’m starting with Unity and exploring the 2D Platformer example project to learn some things. I’m already porting it to Windows Phone(just to get experience).
I made GUI buttons and Rects to control the hero. All the buttons are working fine, but the move left and move right buttons dont play the “Run” animation. Looking at the scripts I can see that they use triggers to run animations,
like anim.SetTrigger("Jump");
, so I opened the Animation Controller named character and added a new Trigger to the parameters called “Run”, on the scripts I added the following code to the buttons script: anim.SetTrigger("Run");
.
The buttons are working fine, but they dont play the run animation, it looks like the hero is floating on the ground.
Here is the buttons code:
if (GUI.RepeatButton(new Rect(250,Screen.height - 200,200,200), rightIcon, framestyle))
{
float h = 1;
anim.SetFloat("Speed", Mathf.Abs(h));
if(h * rigidbody2D.velocity.x < maxSpeed){
// ... add a force to the player.
rigidbody2D.AddForce(Vector2.right * h * moveForce);
}
//Debug.Log ("velocity.x :" + rigidbody2D.velocity.x);
// If the player's horizontal velocity is greater than the maxSpeed...
if(Mathf.Abs(rigidbody2D.velocity.x) > maxSpeed)
// ... set the player's velocity to the maxSpeed in the x axis.
rigidbody2D.velocity = new Vector2(Mathf.Sign(rigidbody2D.velocity.x) * maxSpeed, rigidbody2D.velocity.y);
// If the input is moving the player right and the player is facing left...
if(h > 0 && !facingRight)
// ... flip the player.
Flip();
// Otherwise if the input is moving the player left and the player is facing right...
else if(h < 0 && facingRight)
// ... flip the player.
Flip();
}
if (GUI.RepeatButton(new Rect (50,Screen.height - 200,200,200), leftIcon, framestyle))
{
float h = -1;
anim.SetFloat("Speed", Mathf.Abs(h));
if(h * rigidbody2D.velocity.x < maxSpeed){
// ... add a force to the player.
rigidbody2D.AddForce(Vector2.right * h * moveForce);
}
//Debug.Log ("velocity.x :" + rigidbody2D.velocity.x);
// If the player's horizontal velocity is greater than the maxSpeed...
if(Mathf.Abs(rigidbody2D.velocity.x) > maxSpeed)
// ... set the player's velocity to the maxSpeed in the x axis.
rigidbody2D.velocity = new Vector2(Mathf.Sign(rigidbody2D.velocity.x) * maxSpeed, rigidbody2D.velocity.y);
// If the input is moving the player right and the player is facing left...
if(h > 0 && !facingRight)
// ... flip the player.
Flip();
// Otherwise if the input is moving the player left and the player is facing right...
else if(h < 0 && facingRight)
// ... flip the player.
Flip();
}
It’s inside the OnGUI() of the PlayerController and I defined all the variables. I think that I need to attach the “Run” trigger to the “Run” animation, but I don’t know how.
Someone can help me?