Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.93 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class CharacterController2D : MonoBehaviour
  6. {
  7.     public GameObject ground;
  8.  
  9.     private Rigidbody2D rb;
  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.         ground = GameObject.Find("Ground");
  24.  
  25.         rb = gameObject.GetComponent<Rigidbody2D>();
  26.  
  27.         movementSpeed = 5;
  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(directionValue != 0)
  43.         {
  44.             MoveCharacter();
  45.         }
  46.  
  47.  
  48.         if(Input.GetKeyDown(jumpKey) && isGrounded == true)
  49.         {
  50.             tickJump = true;
  51.         }
  52.     }
  53.  
  54.  
  55.     private void FixedUpdate()
  56.     {
  57.         if (gameObject.GetComponent<BoxCollider2D>().IsTouching(ground.GetComponentInChildren<BoxCollider2D>()))
  58.         {
  59.             isGrounded = true;
  60.         }
  61.         else
  62.         {
  63.             isGrounded = false;
  64.         }
  65.  
  66.  
  67.         if(tickJump == true)
  68.         {
  69.             rb.AddForce(Vector2.up * jumpForce * Time.deltaTime, ForceMode2D.Impulse);
  70.  
  71.             tickJump = false;
  72.         }
  73.     }
  74.  
  75.  
  76.     private void MoveCharacter()
  77.     {
  78.         Transform characterTransform = gameObject.transform;
  79.  
  80.         Vector3 newPosition = Vector3.zero;
  81.  
  82.  
  83.         newPosition.Set(directionValue * movementSpeed, 0, 0);
  84.  
  85.  
  86.         characterTransform.position += newPosition * Time.deltaTime;
  87.     }
  88.  
  89.  
  90.     private IEnumerator JumpEvent()
  91.     {
  92.         do
  93.         {
  94.             yield return null;
  95.         }
  96.  
  97.         while (rb.velocity.y != 0 && isGrounded != true);
  98.  
  99.  
  100.         isGrounded = true;
  101.     }
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement