Question by
SollerEtFortis · Jan 27, 2020 at 08:04 PM ·
scripting problemfpsjumping
I am trying to make character jump in my FPS game. However, he only jumps small height and gets back down to the ground almost immediately. Can anyone help me with the script?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class PlayerMovement : MonoBehaviour
{
private CharacterController _characterController;
// Variables for player movement
public float movementSpeed = 150.0f;
public float gravity = -9.81f;
public float jumpForce = 20.0f;
//Ground Check variables
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
public bool isGrounded;
void Start()
{
_characterController = GetComponent<CharacterController>();
}
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask); //Checks if player is grounded
if (isGrounded) {
float deltaX = Input.GetAxisRaw("Horizontal") * movementSpeed; // If player is grounded, Get Input keys for moving the player
float deltaZ = Input.GetAxisRaw("Vertical") * movementSpeed;
Vector3 movement = new Vector3(deltaX, 0, deltaZ);
movement = Vector3.ClampMagnitude(movement, movementSpeed);
movement.y = gravity; //Sets y component as -9.81
if (Input.GetButtonDown("Jump1")) //Get Input key for jumping
{
movement.y = Mathf.Sqrt(jumpForce * -2.0f * gravity); //Calculate movement with physics as ----> Sqrt(h * (-2) *g)
}
movement *= Time.deltaTime;
movement = transform.TransformDirection(movement);
_characterController.Move(movement);
}
}
}
Comment
Best Answer
Answer by lgarczyn · Jan 28, 2020 at 06:57 PM
CharacterController.Move only affects the next frame. If you want jump physics, you need a velocity that is stored across frames.
declare:
public float verticalVelocity;
and then change your code to:
if (_characterController.isGrounded && Input.GetButtonDown("Jump1"))
verticalVelocity = Mathf.Sqrt(jumpForce * -2.0f * gravity);
else if (_characterController.isGrounded)
verticalVelocity = 0f;
else
verticalVelocity += gravity * Time.fixedDeltaTime;
movement.y = verticalVelocity;
I found a workaround already, but I have tried your piece of code, and it works! Thank you.
Your answer
Follow this Question
Related Questions
About mobile FPS Sprint 1 Answer
player not able to double jump 0 Answers
How to get jumping to return to 0,0,0 quicker 0 Answers
Angle calculation for raycast shotgun weapon ? 1 Answer
Character's jumping mechanism stuck into something invisible 1 Answer