Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class 2DPlayerController : MonoBehaviour
- {
- [SerializeField] private float speed = 40f;
- [SerializeField] private float jumpForce = 8f;
- [SerializeField] private float jumpTime = 0.35f;
- [SerializeField] private float doubleJumpTime = 0.15f;
- [SerializeField] private int maxJumps = 2;
- [SerializeField] public Transform groundCheck;
- [SerializeField] public LayerMask whatIsGround;
- private float moveInput;
- private float jumpTimeCounter;
- private int remainingJumps;
- private bool toJump;
- private Rigidbody2D rbody;
- private void Awake() {
- rbody = GetComponent<Rigidbody2D>();
- }
- private void Update() {
- moveInput = Input.GetAxisRaw("Horizontal");
- if (moveInput > 0) {
- transform.eulerAngles = new Vector3(0, 0, 0);
- }
- else if (moveInput < 0) {
- transform.eulerAngles = new Vector3(0, 180, 0);
- }
- if (Input.GetButtonDown("Jump")) {
- if (remainingJumps == maxJumps) {
- jumpTimeCounter = jumpTime;
- }
- else {
- jumpTimeCounter = doubleJumpTime;
- }
- remainingJumps--;
- }
- if (Input.GetButton("Jump") && remainingJumps > -1) {
- if (jumpTimeCounter > 0) {
- toJump = true;
- jumpTimeCounter -= Time.deltaTime;
- }
- }
- else {
- Collider2D[] colliders = Physics2D.OverlapBoxAll(groundCheck.position, new Vector3(0.9f, 0.1f, 0), whatIsGround);
- for (int i = 0; i < colliders.Length; i++) {
- if (colliders[i].gameObject != gameObject) {
- remainingJumps = maxJumps;
- }
- }
- }
- }
- private void FixedUpdate() {
- rbody.velocity = new Vector2(moveInput * speed, rbody.velocity.y);
- if (toJump) {
- rbody.velocity = new Vector2(rbody.velocity.x, jumpForce);
- toJump = false;
- }
- }
- private void OnDrawGizmos() {
- Gizmos.DrawCube(groundCheck.position, new Vector3(0.9f, 0.1f, 0));
- Gizmos.color = Color.red;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement