How to add double jump to my movement script in unity3d?

Viewed 90

Im trying to learn coding and watch youtube tutorials learn to code and I came across this code that I put in my prototype game, Im just asking what should I add to make my character do a double jump?

Code:

public class fpsmovement : MonoBehaviour
{


private float yaw = 0.0f, pitch = 0.0f;
private Rigidbody rb;

[SerializeField] float movementspeed = 5.0f, sensitivity = 2.0f;
// Start is called before the first frame update
void Start()
{
    Cursor.lockState = CursorLockMode.Locked;
    rb = gameObject.GetComponent<Rigidbody>();
}

// Update is called once per frame
void Update()
{
    if (Input.GetKey(KeyCode.Space) && Physics.Raycast(rb.transform.position, Vector3.down, 1 + 0.001f))
        rb.velocity = new Vector3(rb.velocity.x, 5.0f, rb.velocity.z);
    Look(); 
}

void FixedUpdate()
{
    Movement();  
}

void Look()
{
    pitch -= Input.GetAxisRaw("Mouse Y") * sensitivity;
    pitch = Mathf.Clamp(pitch, -90.0f, 90.0f);
    yaw += Input.GetAxisRaw("Mouse X") * sensitivity;
    Camera.main.transform.localRotation = Quaternion.Euler(pitch, yaw, 0);
}

void Movement()
{
    Vector2 axis = new Vector2(Input.GetAxis("Vertical"), Input.GetAxis("Horizontal")).normalized * movementspeed;
    Vector3 forward = new Vector3(-Camera.main.transform.right.z, 0.0f, Camera.main.transform.right.x);
    Vector3 wishDirector = (forward * axis.x + Camera.main.transform.right * axis.y + Vector3.up * rb.velocity.y);
    rb.velocity = wishDirector;
}

}

2 Answers

First of all you need to check if your player is grounded to be allowed to jump. You problably have a player which can jump again forever like a rocket right now. Then you need to create a boolean variable to check if the player can double jump. Set the variable to true when you jump and set the variable to false when you do the 2nd jump. Also, to allow jump, you should check if the player is grounded OR if can doublejump. There is a lot of tutorials on youtube about this topic, I hope you find the code needed easily.

You can try two methods, "Jump" and "Jump1", the first "Jump" method first uses if to judge whether it is on the ground, if it is allowed to jump on the ground, the "Jump1" method judges if it is not on the ground. On this basis, the code logic for judging the jump state is implemented, and finally the button is reset.

Related