That’s what I figured.
If you jump, you don’t stop in the air, though. At some point, you get a negative velocity due to the gravity which pulls you down. Even if it’s just for a brief moment, _rigidBody.velocity.y > 0
would get evaluated to false. That’s what I meant. If the player keeps hitting the space key fast enough, the result could be this:
Or did you add a condition for that case, too?
I’m still wondering why you did not achieve the desired result with if (Input.GetKeyDown(KeyCode.Space))
. Maybe try direction.y = JumpSpeed;
instead of direction.y *= JumpSpeed;
as you probably don’t want to accellerate the player.
I’m relatively sure that you are able to achieve the desired result with Unity’s methods because you ‘just’ try to implement typical game mechanics. Unity would not be as popular as it is if typical game mechanics do not work well.
Here is an edited version of your Mover class. I outsourced the user input to Update to avoid data loss, and I simplified the code a bit because Unity has a shortcut for checking WASD and arrow keys. This modified structure will hopefully help you implement and test your ideas faster. Since I did not test the code, it might be that it does not work well.
Edited Mover class
using UnityEngine;
namespace Scenes.Player
{
public class Mover : MonoBehaviour
{
private const float SPEED = 12f;
private const float JUMP_SPEED = 200f;
private Rigidbody _rigidBody;
// user input
private float _xInput, _yInput;
private bool _shallJump;
private void Start()
{
_rigidBody = GetComponent<Rigidbody>();
}
private void Update()
{
ProcessUserInput();
}
private void FixedUpdate()
{
Move();
}
private void ProcessUserInput()
{
// Alternatively, you can check all keys manually as you did
// but the typical input keys are mapped to GetAxis.
_xInput = Input.GetAxis("Horizontal");
_yInput = Input.GetAxis("Vertical");
_shallJump = Input.GetKeyDown(KeyCode.Space);
}
private void Move()
{
// Check if jumping
// if player has y-velocity, he is jumping
// and not allowed to move via key input
if (Mathf.Abs(_rigidBody.velocity.y) > 0.01f) { return; }
Vector3 movement = new Vector3(
_xInput * SPEED,
_shallJump ? JUMP_SPEED : 0f,
_yInput * SPEED
);
_rigidBody.AddForce(movement);
_shallJump = false;
}
}
}