Advertisement
evelynshilosky

PlayerMovement - Part 21

Oct 31st, 2023
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.22 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.     private Vector3 lastPosition = new Vector3(0f, 0f, 0f);
  22.     public bool isMoving;
  23.  
  24.  
  25.     // Update is called once per frame
  26.     void Update()
  27.     {
  28.         if (!InventorySystem.Instance.isOpen && !CraftingSystem.Instance.isOpen && !MenuManager.Instance.isMenuOpen) //To Lock PlayerMovement when screen is open
  29.         {
  30.             //checking if we hit the ground to reset our falling velocity, otherwise we will fall faster the next time
  31.             isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
  32.  
  33.             if (isGrounded && velocity.y < 0)
  34.             {
  35.                 velocity.y = -2f;
  36.             }
  37.  
  38.             float x = Input.GetAxis("Horizontal");
  39.             float z = Input.GetAxis("Vertical");
  40.  
  41.             //right is the red Axis, foward is the blue axis
  42.             Vector3 move = transform.right * x + transform.forward * z;
  43.  
  44.             controller.Move(move * speed * Time.deltaTime);
  45.  
  46.             //check if the player is on the ground so he can jump
  47.             if (Input.GetButtonDown("Jump") && isGrounded)
  48.             {
  49.                 //the equation for jumping
  50.                 velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
  51.             }
  52.  
  53.             velocity.y += gravity * Time.deltaTime;
  54.  
  55.             controller.Move(velocity * Time.deltaTime);
  56.  
  57.             if (lastPosition != gameObject.transform.position && isGrounded == true)
  58.             {
  59.                 isMoving = true;
  60.                 SoundManager.Instance.PlaySound(SoundManager.Instance.grassWalkSound);
  61.             }
  62.             else
  63.             {
  64.                 isMoving = false;
  65.                 SoundManager.Instance.grassWalkSound.Stop();
  66.             }
  67.             lastPosition = gameObject.transform.position;
  68.         }
  69.     }
  70.  
  71.  
  72.  
  73. }
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement