public class movement : MonoBehaviour
{
private Rigidbody2D rb;
private Animator an;
private Collider2D collid;
[SerializeField] private LayerMask ground;
private enum State {idle, running, jumping, falling}
private State state = State.idle;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
an = GetComponent<Animator>();
collid = GetComponent<Collider2D>();
}
private void Update()
{
float hDirection = Input.GetAxis("Horizontal");
if (hDirection < 0)
{
rb.velocity = new Vector2(-10, rb.velocity.y);
transform.localScale = new Vector2(-1, 1);
}
else if ((hDirection > 0))
{
rb.velocity = new Vector2(10, rb.velocity.y);
transform.localScale = new Vector2(1, 1);
}
if (Input.GetButtonDown("Jump") && collid.IsTouchingLayers(ground))
{
rb.velocity = new Vector2(rb.velocity.x, 50f);
state = State.jumping;
}
VelocityState();
an.SetInteger("state",(int)state);
}
private void VelocityState()
{
if (state == State.jumping)
{
if (rb.velocity.y < 0.1f) ;
{
state = State.falling;
}
}
else if (state == State.falling)
{
if(collid.IsTouchingLayers(ground))
{
state = State.idle;
}
}
else if (Mathf.Abs(rb.velocity.x) > Mathf.Epsilon)
{
// moving
state = State.running;
}
else
{
state = State.idle;
}
}
}