Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice

Question How do I stop the player from moving mid-air using this script

Discussion in 'Getting Started' started by TheThirdHorseman, Mar 25, 2022.

  1. TheThirdHorseman

    TheThirdHorseman

    Joined:
    Jan 4, 2022
    Posts:
    1
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Movement : MonoBehaviour
    6. {
    7.     private Vector3 PlayerMovementInput;
    8.     [SerializeField] private LayerMask FloorMask;
    9.     private Transform FeetTransform;
    10.     private Rigidbody PlayerBody;
    11.     [Space]
    12.     private float moveSpeed = 0f;
    13.     [SerializeField] private float Speed = 5f;
    14.     [SerializeField] private float SprintSpeed = 7f;
    15.     [SerializeField] private float JumpForce;
    16.     private bool isGrounded;
    17.  
    18.     private void Start()
    19.     {
    20.         FeetTransform = this.transform.GetChild(1).transform;
    21.         PlayerBody = GetComponent<Rigidbody>();
    22.     }
    23.  
    24.     void Update()
    25.     {
    26.         isGrounded = Physics.CheckSphere(FeetTransform.position, 0.1f, FloorMask);
    27.  
    28.         PlayerMovementInput = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
    29.         MovePlayer();
    30.         if (Input.GetKeyDown(KeyCode.LeftControl))
    31.         {
    32.             Vector3 MoveVector2 = transform.TransformDirection(PlayerMovementInput) * SprintSpeed;
    33.             PlayerBody.velocity = new Vector3(MoveVector2.x, PlayerBody.velocity.y, MoveVector2.z);
    34.         }
    35.     }
    36.  
    37.     private void MovePlayer()
    38.     {
    39.         if (Input.GetKey(KeyCode.LeftControl))
    40.         {
    41.             moveSpeed = SprintSpeed;
    42.         }
    43.         else
    44.         {
    45.             moveSpeed = Speed;
    46.         }
    47.  
    48.         Vector3 MoveVector = transform.TransformDirection(PlayerMovementInput) * moveSpeed;
    49.         PlayerBody.velocity = new Vector3(MoveVector.x, PlayerBody.velocity.y, MoveVector.z);
    50.  
    51.         if (Input.GetKeyDown(KeyCode.Space))
    52.         {
    53.             if (isGrounded)
    54.             {
    55.                 PlayerBody.AddForce(Vector3.up * JumpForce, ForceMode.Impulse);
    56.             }
    57.  
    58.         }
    59.     }
    60. }
    61.