GregLeck

Untitled

Jan 7th, 2020
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.64 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. public class CharacterJump : MonoBehaviour
  4. {
  5.     private CharacterController characterController;
  6.  
  7.     private float movementSpeed = 5.0f;
  8.     private float horizontalInput;
  9.     private Vector3 movement;
  10.  
  11.     // Jump
  12.     private float jumpHeight = 0.5f;
  13.     private float gravity = 0.045f;
  14.     private bool jump = false;
  15.  
  16.     private void Start()
  17.     {
  18.         characterController = GetComponent<CharacterController>();
  19.     }
  20.  
  21.     private void Update()
  22.     {
  23.         horizontalInput = Input.GetAxis("Horizontal");
  24.  
  25.         if (!jump && Input.GetButtonDown("Jump"))
  26.         {
  27.             jump = true;
  28.         }
  29.     }
  30.  
  31.     private void FixedUpdate()
  32.     {
  33.         movement.x = horizontalInput * movementSpeed * Time.deltaTime;
  34.  
  35.         // Check if characterController is not grounded
  36.         // and add gravity
  37.         if (!characterController.isGrounded)
  38.         {
  39.             if (movement.y > 0)
  40.             {
  41.                 // As we go up, apply normal gravity
  42.                 movement.y -= gravity;
  43.             }
  44.             else
  45.             {
  46.                 // As we go down, apply "faster" gravity
  47.                 movement.y -= gravity * 1.5f;
  48.             }
  49.         }
  50.         else
  51.         {
  52.             movement.y = 0;
  53.         }
  54.  
  55.         // Setting jumpHeight to movement.y
  56.         if (jump)
  57.         {
  58.             movement.y = jumpHeight;
  59.             jump = false;
  60.         }
  61.  
  62.         // Check if characterController exists and
  63.         // then move player according to input
  64.         if (characterController)
  65.         {
  66.             characterController.Move(movement);
  67.         }
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment