Advertisement
evelynshilosky

PlayerMovement - Part 1

Jun 2nd, 2024
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.43 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class PlayerMovement : MonoBehaviour
  6. {
  7.     public CharacterController controller;
  8.  
  9.     public float speed = 12f;
  10.     public float gravity = -9.81f * 2;
  11.     public float jumpHeight = 3f;
  12.  
  13.     public Transform groundCheck;
  14.     public float groundDistance = 0.4f;
  15.     public LayerMask groundMask;
  16.  
  17.     Vector3 velocity;
  18.  
  19.     bool isGrounded;
  20.  
  21.     // Update is called once per frame
  22.     void Update()
  23.     {
  24.         //checking if we hit the ground to reset our falling velocity, otherwise we will fall faster the next time
  25.         isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
  26.  
  27.         if (isGrounded && velocity.y < 0)
  28.         {
  29.             velocity.y = -2f;
  30.         }
  31.  
  32.         float x = Input.GetAxis("Horizontal");
  33.         float z = Input.GetAxis("Vertical");
  34.  
  35.         //right is the red Axis, foward is the blue axis
  36.         Vector3 move = transform.right * x + transform.forward * z;
  37.  
  38.         controller.Move(move * speed * Time.deltaTime);
  39.  
  40.         //check if the player is on the ground so he can jump
  41.         if (Input.GetButtonDown("Jump") && isGrounded)
  42.         {
  43.             //the equation for jumping
  44.             velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
  45.         }
  46.  
  47.         velocity.y += gravity * Time.deltaTime;
  48.  
  49.         controller.Move(velocity * Time.deltaTime);
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement