Greetings.
I am attempting to build a simple 3d platformer to practice what I’ve learned. Right now I have a small cube as the player character who can move around and jump. Next, I am trying to implement a mechanic where the player can hold down the Z button to stop their velocity; then when they let go, they’ll resume the velocity they were going. I am also implementing a mechanic where they can hold the X button and, upon release, they’ll head in the opposite direction. With the code I have now, it works but only occasionally. Here is my code for these two mechanics; I’ve placed them in FixedUpdate.
if (Input.GetKeyDown(KeyCode.Z))
{
velStorage = rb.velocity;
allowMovement = false;
rb.useGravity = false;
signal = true;
rb.velocity = Vector3.zero;
}
/*
if (Input.GetKey(KeyCode.Z))
{
rb.velocity = new Vector3(0f,0f,0f);
rb.useGravity = false;
}
*/
if (Input.GetKeyUp(KeyCode.Z))
{
rb.velocity = velStorage;
allowMovement = true;
rb.useGravity = true;
signal = false;
velStorage = Vector3.zero;
}
if (Input.GetKeyDown(KeyCode.X))
{
allowMovement = false;
antiVelStorage = -rb.velocity;
rb.velocity = Vector3.zero;
rb.useGravity = false;
antiSignal = true;
}
/*
if (Input.GetKey(KeyCode.X))
{
rb.velocity = new Vector3(0f, 0f, 0f);
rb.useGravity = false;
}
*/
if (Input.GetKeyUp(KeyCode.X))
{
allowMovement = true;
rb.velocity = antiVelStorage;
antiVelStorage = Vector3.zero;
rb.useGravity = true;
antiSignal = false;
}
The problem I am experiencing is ocasionally the returned velocity will be Vector3.zero. Also sometimes when I release the button it won’t call the second if statement (for either of the mechanics) and the cube will just float there in zero gravity until I press either of the buttons again. So to me, it seems that either my computer or Unity is having trouble regeristering the Inputs from the Z & X Button. I’m wondering if there is a different way to code this or if there is a preference I can switch in Unity that’ll make the Input more consistent.
Thanks Much!