I have a simple jumping action in my game. The player presses jump, gets launched into the air, transitions to an air-state and falls down to ground again. The usual stuff.
However, if the player lands on the ground and the user is still holding the jump key, the player automatically jumps again upon landing. I don't want that. I want the user to let go of the key before being able to jump again.
Here's a simplified version of my player movement code, with only the nessessary stuff in.
public class GenesisPhysics : MonoBehaviour {
public bool isGrounded = true;
public bool jumpIsPressed;
public IA inputActions; // New input system's Input Action Asset C# class
private void Awake()
{
inputActions = new IA();
// Movement actions stuff...
inputActions.PlayerControls2D.Jump.performed = jumpContext => jumpIsPressed = true;
inputActions.PlayerControls2D.Jump.canceled = jumpContext => jumpIsPressed = false;
}
private void FixedUpdate()
{
if(isGrounded)
{
ExecuteGroundStateLoop()
} else {
ExecuteAirStateLoop()
}
}
private void ExecuteGroundStateLoop()
{
// Do stuff...
if(jumpPressed) {
isGrounded = false;
// Set x and y speeds to be applied in Air state
} else {
// Do some more stuff...
}
}
private void ExecuteAirStateLoop()
{
// Applying gravity, jump force, checking for ground and other stuff...
// If ground is found, set isGrounded to true.
}
void OnEnable()
{
inputActions.Enable()
}
void OnDisable()
{
inputActions.Disable()
}
}
This might not be enough code to fix the issue. I'll update this post if more is needed.
CodePudding user response:
Create a new bool variable "jumpPressAvailable" and set it to true in the beginning. Use this new variable to control, if a jump is available. For example, if jump button is pressed, set "jumpPressAvailable" to false, and if jump button is released or "NOT pressed", set "jumpPressAvailable" to true again. A jump can only be started if jump button is pressed and "jumpPressAvailable" is true.
public bool jumpPressAvailable=true;
Add some lines in the Ground State Loop:
if(jumpPressed && jumpPressAvailable) {
isGrounded = false;
jumpPressAvailable = false;
// Set x and y speeds to be applied in Air state
} else {
if(jumpPressed == false)
{
jumpPressAvailable = true;
}
// Do some more stuff...
}