I'm working on a test project to experiment with Rigidbody in Unity. I worked on horizontal movement and jump actions, but I have a problem. Input.GetKeyDown() seems to not catch my key down event most of the time. I tried looking at possible solutions that suggested catching key inputs in Update() and corresponding with Rigidbody interactions with FixedUpdate(). When I tried this, I saw little to no improvement. Here is the script I'm working on right now:
public class PlayerScript : MonoBehaviour
{
[SerializeField] private float jumpConstant = 5.0f;
[SerializeField] private int walkSpeed = 10;
private bool jumpDown;
private float horizontalInput;
private Rigidbody rbComponent;
// Start is called before the first frame update
void Start()
{
rbComponent = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
CheckIfJumpKeyPressed();
GetHorizontalInput();
}
void FixedUpdate()
{
JumpIfKeyPressed();
MoveHorizontal();
}
void CheckIfJumpKeyPressed()
{
jumpDown = Input.GetKeyDown(KeyCode.Space);
}
void JumpIfKeyPressed()
{
if (jumpDown)
{
jumpDown = false;
rbComponent.AddForce(Vector3.up * jumpConstant, ForceMode.VelocityChange);
Debug.Log("Jumped!");
}
}
void GetHorizontalInput()
{
horizontalInput = Input.GetAxis("Horizontal");
}
void MoveHorizontal()
{
rbComponent.velocity = new Vector3(horizontalInput * walkSpeed, rbComponent.velocity.y, 0);
}
}
Thank you in advance.