fbpx

 

Jump while running ...
 

Jump while running not faster than normal jump. Any help with the code?  

   RSS

0

Hi everyone!

I found and adapted this piece of code to create a simple character controller. Everything works as I need except for jump: if the character walks (or stands still) and then jump there are no problems but if I make it run and then press the jump button, the jump movement is identical to when it walks. I expect him to have a longer and faster jump but it doesn't happen!

Here's the code (please ignore everything related to the animator):

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerControllerMouseNOROOT : MonoBehaviour
{
public CharacterController controller;
private Animator anim;
private float x = 0.0f;
private float z = 0.0f;

[SerializeField] private float walkSpeed = 2.0f;
[SerializeField] private float runSpeed = 6.0f;
[SerializeField] private float jumpHeight = 3.0f;
[SerializeField] private float rotSpeed = 4.0f;

private float speed = 0.0f;
private float rotation = 0.0f;

[SerializeField] private Transform groundCheck;
[SerializeField] private float groundDistance = 0.4f;
[SerializeField] private LayerMask groundMask;
public bool isGrounded;
[SerializeField] private float gravity = -19.62f;
private Vector3 velocity;

// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
anim = GetComponent<Animator>();
}

// Update is called once per frame
void Update()
{
// Check to see if player is grounded
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

if (isGrounded && velocity.y < 0)
{
velocity.y = -2.0f;
anim.SetBool("isGrounded", true);
}

// Player movement and sprint
x = Input.GetAxis("Horizontal");
z = Input.GetAxis("Vertical");
rotation = x;
anim.SetFloat("Rotation", rotation);

if (z != 0f)
{
if (z > 0)
{
speed = walkSpeed;
anim.SetFloat("Speed", 1.0f);
}
else
{
speed = walkSpeed;
anim.SetFloat("Speed", -1.0f);
}

if (Input.GetButton("Sprint") && isGrounded && z > 0)
{
speed = runSpeed;
anim.SetFloat("Speed", 2.0f);
}
}
else
{
speed = 0f;
anim.SetFloat("Speed", 0f);
}

Vector3 move = Vector3.Normalize(transform.right * x + transform.forward * z);

move *= speed;

velocity.y += gravity * Time.deltaTime;

controller.Move(move * Time.deltaTime);

controller.Move(velocity * Time.deltaTime);

transform.Rotate(0, x * rotSpeed, 0);

// Jump
if (Input.GetButtonDown("Jump") && isGrounded)
{
isGrounded = false;
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
anim.SetTrigger("isJumping");
anim.SetBool("isGrounded", false);
}

}

}

 

Thank you in advance for your help!

Share:

 

 

Scroll to Top

Please Login or Register