I am using a basic jump script to make my character jump. I am checking to make sure he is grounded before jumping to prevent the multiple jump scenario. I am also preventing the changing of rotation while they jump (to prevent them from ‘turning’ during a jump).
Everything works great, but one thing bugs me. If the player is running (by pressing the right arrow key in my game) and then jumps he jumps forward, but if he let’s go of the right arrow key he stops in mid-air. He can also jump straight up and then press the right arrow key to move forward .
How can I make it so that if the person is already moving forward when they jump, they are forced to keep moving forward until they are back on solid ground?
Here is my code in C-Sharp. Thanks for taking a look:
using UnityEngine;
using System.Collections;
public class PlayerJump : MonoBehaviour {
public float distToGround;
public float jumpSpeed;
private Rigidbody rb;
private CapsuleCollider collider;
void Awake()
{
jumpSpeed = 6.0f;
rb = GetComponent<Rigidbody>();
collider = GetComponent<CapsuleCollider>();
}
void Start()
{
distToGround = collider.bounds.extents.y; // get the distance to ground
}
void Update ()
{
if (Input.GetKeyDown (KeyCode.Space) && IsGrounded())
{
rb.velocity += Vector3.up * jumpSpeed;
}
}
bool IsGrounded()
{
return Physics.Raycast(transform.position, -Vector3.up, distToGround + 0.1f);
}
}
By adding something like “isGrounded”, you’re essentially creating a state machine where movement differs depending on the object’s current state. That being the case, it’s easy enough to make the movement differ in that, while not in the “isGrounded” state, player input no longer affects it. This is a common enough setup.
Since you’re going to be referencing your state machine from both this script and your “general movement” script, there’s really no need to separate them. Give jump its own function rather than being in update and move all input-related commands to a higher-level script called PlayerInput or something which just calls functions in your “player” object’s CharacterMovement script (or w/e it’s called), which is the one you’ll combine this one with.
Thank you. Taking your advice Lysander I was able to make my player continue to move forward while jumping even without the user pressing a movement key.