- Home /
Question by
GodsStrength · Apr 14, 2020 at 02:25 PM ·
movementplayerjumpjumpingplayer movement
How to prevent player from moving in air while jumping in place??
Hi. I made a new project and I'm working on the movement of my first person character.
When you hold WASD or arrow keys the player moves normally. When you hold Left shift and WASD or arrow keys together the player sprints (doubles the run speed) When you press space the player jumps whether it is moving or stopped(Jump speed in X axis is same as normal speed) When you are sprinting and you press space, also the jump speed in X axis is doubled (Same as sprint speed)
My main problem is that when I press space to jump while the player is not moving, after player gets in air, it still moves in air (which is not realistic)
How to solve that ??
Here is the code
public class PlayerMovement : MonoBehaviour { public CharacterController controller;
public float normalSpeed = 8f;
public float sprintSpeed = 16f;
float currentspeed = 0;
public float gravity = -40f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
public float JumpHeight = 3f;
Vector3 velocity;
bool isGrounded;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(velocity * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
if (Input.GetKey(KeyCode.LeftShift) && isGrounded)
{
currentspeed = sprintSpeed;
controller.Move(move * currentspeed * Time.deltaTime); // Sprint Movement Speed
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(JumpHeight * -2 * gravity);
}
}
else if (Input.GetKey(KeyCode.LeftShift) && isGrounded == false)
{
currentspeed = sprintSpeed;
controller.Move(move * currentspeed * Time.deltaTime); // Sprint Movement Speed
}
else
{
currentspeed = normalSpeed;
controller.Move(move * currentspeed * Time.deltaTime); // Normal Movement Speed
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(JumpHeight * -2 * gravity);
}
}
}
}
Comment