using UnityEngine; public class PlayerCat : MonoBehaviour { // How strong force to apply for sidewise movement public float movementForce = 15; // How strong force to apply for jump public float jumpForce = 5; // Where should we check for ground public Transform groundCheck; // Are we standing on the ground? private bool grounded; // References for various components to use later private SpriteRenderer sr; private Rigidbody2D rb; private Animator anim; // Use this for initialization void Start() { // Find our components sr = GetComponent<SpriteRenderer>(); rb = GetComponent<Rigidbody2D>(); anim = GetComponent<Animator>(); } // Update is called once per frame void Update() { // Lets see if we are standing on something grounded = Physics2D.OverlapPoint(groundCheck.position) != null; // Jump only when we are grounded if (Input.GetButtonDown("Jump") && grounded) { rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse); } // Set Speed parameter to absolute value of our horizontal speed anim.SetFloat("Speed", Mathf.Abs(rb.velocity.x)); } // FixedUpdate is called every Time.fixedDeltaTime void FixedUpdate() { // Get value of horizontal axis (left/right arrow or a/d keys), // returns value in range [-1.0f, 1.0f] var h = Input.GetAxis("Horizontal"); // Flip sprite depending on horizontal input if (h < 0.0f) sr.flipX = true; if (h > 0.0f) sr.flipX = false; // Move player according to horizontal axis rb.AddForce(Vector2.right * h * movementForce, ForceMode2D.Force); } }Then, add empty GameObject to the cat, rename it to GroundCheck and place it right below cat's Capsule Collider.
Lets make jumps look nicer by adding different animation for when the cat is in the air. Prepare cat_jump bitmap like before, by slicing it and creating animation out of it. This time, make animation only out of 3rd and 4th frames. Like before, you can delete cat_jump_2 GameObject and cat_jump_2 Animator that unity created.
// Update is called once per frame void Update() { // Lets see if we are standing on something grounded = Physics2D.OverlapPoint(groundCheck.position) != null; // Jump only when we are grounded (Space key by default) if (Input.GetButtonDown("Jump") && grounded) { rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse); } // Set Speed parameter to absolute value of our horizontal speed anim.SetFloat("Speed", Mathf.Abs(rb.velocity.x)); // Set Grounded animator parameter anim.SetBool("Grounded", grounded); }Congratulations, you taught our cat how to jump properly :3
Of course we could continue improving our jump by adding animation for beginning of the jump and landing, but its not really necessary and it would complicate cat Animator. If you are curious how much, take a look at one that has them implemented.
No comments:
Post a Comment