[Solved] Prevent movement while in the air while keeping momentum.
I had an issue with locking my directional input but keeping my momentum when a player jumps, but I found a solution that seems to do the trick.
Basically when you jump store your current velocity in a Vector2 (or Vector3 for 3D), then with a ground checker to see if you are not on the found multiply the Vector2/3 with your horizontal axis. if you want to ad any drag then multiply that by another float.something like this:
private void Jump()
{
// gets the velocity you had the moment your jump is called, then jumps your character
currentMomentum = rigidBody2D.velocity;`enter code here`
rigidBody2D.velocity = Vector2.up * jumpForce;
}
void HorizontalMovement()
{
if (isOnGround)
{
// your normal velocity controlled from your input
rigidBody2D.velocity = new Vector2(horizontalMove * moveSpeed, rigidBody2D.velocity.y);
animator.SetFloat("Speed", Mathf.Abs(horizontalMove));
}
else
{
// your velocity calculation using the stored velocity from when you jumped
float dragTime = 1f;
dragTime *= 2f;
rigidBody2D.velocity = new Vector2(currentMomentum.x *dragTime , rigidBody2D.velocity.y);
}
}
You can also do it without any drag and you wont fly off forever.Additionally you can also throw an isJumping bool into the mix so that your momentum is only locked when you jump and not when you fall.
I hope this helps anyone who is looking for a solution like I was.
Your answer
Follow this Question
Related Questions
Adding force to a rigidbody opposite to the direction of a rotating weapon 0 Answers
How to change rigidbody type correctly? Angry Birds Game 1 Answer
Character Controller moving at different Framrates? [Unsolved] 0 Answers
Can I ignore part of a vector3 for physics reasons? 0 Answers
What is the correct way to learn unity scripting ? 2 Answers