Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.91 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class CharacterController2D : MonoBehaviour
  6. {
  7.     private Rigidbody2D rb;
  8.  
  9.     public LayerMask groundLayer;
  10.  
  11.     private float directionValue;
  12.     private float movementSpeed;
  13.     private float jumpForce;
  14.  
  15.     private KeyCode jumpKey;
  16.  
  17.     private bool isGrounded;
  18.     private bool tickJump;
  19.  
  20.  
  21.     private void Awake()
  22.     {
  23.         rb = gameObject.GetComponent<Rigidbody2D>();
  24.  
  25.         groundLayer = LayerMask.GetMask("Ground");
  26.  
  27.         movementSpeed = 500;
  28.         jumpForce = 350;
  29.  
  30.         jumpKey = KeyCode.Space;
  31.  
  32.         isGrounded = true;
  33.         tickJump = false;
  34.     }
  35.  
  36.  
  37.     private void Update()
  38.     {
  39.         directionValue = Input.GetAxisRaw("Horizontal");
  40.  
  41.  
  42.         if(Input.GetKeyDown(jumpKey) && isGrounded == true)
  43.         {
  44.             tickJump = true;
  45.  
  46.             StartCoroutine(JumpEvent());
  47.         }
  48.     }
  49.  
  50.  
  51.     private void FixedUpdate()
  52.     {
  53.         RaycastHit2D hit0 = Physics2D.Raycast(transform.position, Vector2.down, 0.55f, groundLayer);
  54.  
  55.         RaycastHit2D hit1 = Physics2D.Raycast(transform.position + new Vector3(-0.5f, 0, 0), Vector2.down, 0.55f, groundLayer);
  56.  
  57.         RaycastHit2D hit2 = Physics2D.Raycast(transform.position + new Vector3(0.5f, 0, 0), Vector2.down, 0.55f, groundLayer);
  58.  
  59.  
  60.         isGrounded = hit0.collider != null || hit1.collider != null || hit2.collider != null;
  61.  
  62.  
  63.         if (tickJump == true)
  64.         {
  65.             rb.AddForce(Vector2.up * jumpForce * Time.deltaTime, ForceMode2D.Impulse);
  66.  
  67.             tickJump = false;
  68.         }
  69.  
  70.  
  71.         rb.velocity = new Vector2(directionValue * movementSpeed * Time.deltaTime, rb.velocity.y);
  72.     }
  73.  
  74.  
  75.     private IEnumerator JumpEvent()
  76.     {
  77.         do
  78.         {
  79.             yield return null;
  80.         }
  81.  
  82.         while (isGrounded != true);
  83.  
  84.  
  85.         isGrounded = true;
  86.     }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement