Adding momentum to jump while sprinting
I can't figure out how to add momentum when my player jumps while moving. it seems to work fine when i'm not sprinting but if i jump while sprinting it sort of stops mid air and moves the same amount as if i wasn't sprinting.
I was thinking the problem is when i'm jumping the player isn't grounded anymore so the movement speed is being set back to walking speed but i can't figure out hoe to do it.
public class Test : MonoBehaviour { public Camera playerCam;
[SerializeField] private float speed;
[SerializeField] private float walkSpeed;
[SerializeField] private float sprintSpeed;
[SerializeField] private float jumpForce;
[SerializeField] private float jumpRaycastDistance;
private float hAxis;
private float vAxis;
private float baseFOV;
private bool isSprinting;
private Transform player;
private Rigidbody rb;
private void Start()
{
baseFOV = playerCam.fieldOfView;
player = this.transform;
rb = GetComponent<Rigidbody>();
}
private void Update()
{
Jump();
MovementSpeed();
}
private void FixedUpdate()
{
Movement();
}
//player movement
private void Movement()
{
hAxis = Input.GetAxisRaw("Horizontal");
vAxis = Input.GetAxisRaw("Vertical");
Vector3 movement = new Vector3(hAxis, 0, vAxis) * speed * Time.fixedDeltaTime;
Vector3 newPostion = rb.position + rb.transform.TransformDirection(movement);
rb.MovePosition(newPostion);
}
//Movement speeds and camera FOV Change
private void MovementSpeed()
{
if (Input.GetKey(KeyCode.LeftShift) && IsGrounded())
{
isSprinting = true;
speed = sprintSpeed;
if (isSprinting && vAxis > 0)
{
playerCam.fieldOfView = Mathf.Lerp(playerCam.fieldOfView, baseFOV * 1.25f, Time.deltaTime * 6f);
}
}
else
{
isSprinting = false;
playerCam.fieldOfView = Mathf.Lerp(playerCam.fieldOfView, baseFOV, Time.deltaTime * 6f);
speed = walkSpeed;
}
}
//jumping
private void Jump()
{
if(Input.GetButtonDown("Jump"))
{
if (IsGrounded())
{
rb.AddForce(0, jumpForce, 0, ForceMode.VelocityChange);
//rb.velocity += jumpForce * Vector3.up;
}
}
}
//Raycast to check if the player is gronded
private bool IsGrounded()
{
Debug.DrawRay(transform.position, Vector3.down * jumpRaycastDistance, Color.red);
return Physics.Raycast(transform.position, Vector3.down, jumpRaycastDistance);
}
}
Your answer
Follow this Question
Related Questions
Weird behaviour with WASD and arrow keys 1 Answer
Detect if velocity equals 0? 2 Answers
[2D Platform Game] Precise Jumping Without Holding Down Directional Button. 0 Answers
Error CS0120 : An object reference is required to access non-static member 3 Answers
Navmesh interfering with mecanim jump animation (root motion) 1 Answer