using UnityEngine; public class PlayerController : MonoBehaviour { public float walkForce = 50; public float maxWalkSpeed = 5; public float jumpForce = 400; public float groundedCollisionArea = 1f; public LayerMask floorMask; private Rigidbody2D rb; private bool jumped = false; // Start is called before the first frame update void Start() { rb = GetComponent(); } // FixedUpdate is called once per physics frame void FixedUpdate() { /* * JUMPING */ // Check if we are on the ground by drawing a box around the centre of the player character var grounded = Physics2D.OverlapBox(transform.position, Vector2.one * groundedCollisionArea, 0, floorMask); // If we are jumping and have reached the ground and the player isn't holding space anymore, allow jumping again. // Note this would allow buggy super jumping if the player can hammer space fast enough... if (jumped && grounded && !Input.GetKey("space")) { Debug.Log("Jump reset"); jumped = false; } // If we are on the ground and aren't in the middle of a jump. Do a jump. if(grounded && !jumped && Input.GetKey("space")) { Debug.Log("JUMP"); rb.AddForce(Vector2.up * jumpForce); // Prevent jumping until we have hit the ground again jumped = true; } /* * WALKING */ var input = Input.GetAxisRaw("Horizontal"); // Check if the input is in the opposite direction to the player's current direction of travel. // This makes changing direction always happen, including in the air if(Mathf.Sign(input) != Mathf.Sign(rb.velocity.x)) { rb.AddForce(new Vector2(walkForce * input, 0)); } // Only apply more movement speed when the player is below a max speed else if (input != 0f && Mathf.Abs(rb.velocity.x) < maxWalkSpeed) { rb.AddForce(new Vector2(walkForce * input, 0)); } } }