Answer the question
In order to leave comments, you need to log in
Why doesn't jump animation work for platformer on unity 3d?
Hello everyone, now I'm learning to work with unity 3d. One book shows how to make an animated run, how to make a jump, but how to make an animated jump is not already told there. As I understand it, the code and the principle of operation should not differ much from running, so I wrote this code:
public class PlayerController : MonoBehaviour
{
public float speed = 250.0f;
private Rigidbody2D _body;
private Animator _anim;
public float jumpforce = 25.0f;
private BoxCollider2D _box;
// Start is called before the first frame update
void Start()
{
_body = GetComponent<Rigidbody2D>();
_anim = GetComponent<Animator>();
_box = GetComponent<BoxCollider2D>();
}
// Update is called once per frame
void Update()
{
float deltaX = Input.GetAxisRaw("Horizontal") * Time.deltaTime * speed;
float deltaY = Input.GetAxis("Vertical");
Vector2 movement = new Vector2(deltaX, _body.velocity.y);
_body.velocity = movement;
Vector3 max = _box.bounds.max;
Vector3 min = _box.bounds.min;
Vector2 corner1 = new Vector2(max.x, min.y - .1f);
Vector2 corner2 = new Vector2(min.x, min.y - .2f);
Collider2D hit = Physics2D.OverlapArea(corner1, corner2);
bool grounded = false;
if(hit != null)
{
grounded = true;
}
if(grounded && Input.GetKeyDown(KeyCode.Space))
{
_body.AddForce(Vector2.up * jumpforce, ForceMode2D.Impulse);
}
_anim.SetFloat("v_speed", deltaY);
_anim.SetBool("grounded", grounded);
_anim.SetFloat("speed", Mathf.Abs(deltaX));
if(!Mathf.Approximately(deltaX, 0))
{
transform.localScale = new Vector3(Mathf.Sign(deltaX), 1, 1);
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question