Hello, I’m working on a simple cannabalt-style platformer where the character jumps (as most platforming characters do). Up until now, I’ve been using a slightly modified version of the basic character controller found on the Unity Scripting Reference:
using UnityEngine;
using System.Collections;
public class movement : MonoBehaviour {
public float speed = 6.0F;
public float jumpHeight = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
moveDirection = Vector3.forward;
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpHeight;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
For the most part, this worked alright, but my problem with it was that as long as you held down the jump button, the character would keep jumping, but I only want him to jump once per button press. I decided to change the code to this:
using UnityEngine;
using System.Collections;
public class movement : MonoBehaviour {
public float speed = 6.0F;
public float jumpHeight = 8.0F;
public float gravity = 20.0F;
private bool doJump = true;
private Vector3 moveDirection = Vector3.zero;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (Input.GetButtonUp("Jump"))
{
doJump = true;
}
if (controller.isGrounded) {
moveDirection = Vector3.forward;
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButtonDown("Jump") && (doJump = true))
{
moveDirection.y = jumpHeight;
doJump = false;
}
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
For the most part, adding the boolean check seemed to be working fine. The character only jumped once per pressing of the button, and it looked like things were improved. After further testing though, I found a new problem. What’s happening is that if I hit the jump button right after the character lands, it sometimes fails to register at all and the jump doesn’t activate. I tested several times to make sure that something was wrong with the game and that I wasn’t simply hitting the button before he landed completely, and it indeed fails to activate within the first split second or so of landing. Since this is an endless runner, a single missed jump means death, which will be very frustrating if it’s not the player’s fault. My question is, how could I better go about limiting the game to one jump per button press without causing the controls to become glitchy and sometimes unresponsive?