I’m pretty new to unity, and have ran into lots of problems. I want to add multiple jumps into my game, at least a triple jump, but I can’t figure out how to do it to save my life. Can someone help me out, I would be very grateful. This is the code i’m using right now.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public CharacterController2D controller;
public Animator animator;
public float runSpeed = 40f;
float horizontalMove = 0f;
bool jump = false;
// Update is called once per frame
void Update() {
horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
animator.SetFloat("Speed", Mathf.Abs(horizontalMove));
if (Input.GetButtonDown("Jump"))
{
jump = true;
animator.SetBool("IsJumping", true);
}
}
public void OnLanding ()
{
animator.SetBool("IsJumping", false);
}
void FixedUpdate()
{
// Move our character
controller.Move(horizontalMove * Time.fixedDeltaTime, false, jump);
jump = false;
}
}
Heyo,
Alrighty, I’m gonna break it up into a few steps here:
STEP 1
Your code is a decent start to the whole thing, but you’ll need more (obviously). So, let’s look at a few things. What keeps a player from being able to spam the jump button and fly in most games? Well, there’s the requirement of landing on the ground before your next jump. This suggests implementing some kind of ground check would be a good idea. If you googled “Unity Ground Check”, there are a lot of suggestions telling you how you can accomplish this part of the process. It’ll differ slightly depending on whether your project is 3D or 2D.
STEP 2
After you have a ground check implemented, you should be able to allow the user to only jump if they are “grounded” fairly easily. A quick if statement could do the job pretty well. So how might you allow for a double jump? Or a triple jump? Well, What if, you had a little variable keeping track of your REMAINING JUMPS, and every time you land on the ground, it is reset to 3. And then, as long as you have some remaining jumps (remainingJumps != 0), you can click Space (or whatever button you want for jump) to, well, jump. And the you’ll have to make sure to decrease the counter by 1 each time you jump.
Also, to perform the actual jump, using forces and rigidbodies would probably be better and let just a gravitational force pull the character back down to some surface. But if you’re wanting to avoid those physics, there are other ways you could pull off the actual jump. Hopefully this gives you some idea of where to go with this?