Reputation: 109
I just started learning unity maybe a month ago so very new to the language of C#. So I just followed a tutorial for adding more than one jump into my player but after I injected the code he can't jump when moving. He only jumps in the same spot now. I can't figure out the issue.
void Update()
{
HandleInput();
if (isGrounded == true)
{
extraJumps = extraJumpsValue;
}
if (Input.GetKeyDown(KeyCode.Space) && extraJumps > 0)
{
myRigidbody.velocity = Vector2.up * jumpForce;
extraJumps--;
}
else if (Input.GetKeyDown(KeyCode.Space) && extraJumps == 0 && isGrounded == true)
{
myRigidbody.velocity = Vector2.up * jumpForce;
}
}
Upvotes: 0
Views: 61
Reputation: 617
the problem is an overlap happening between the both actions, and since we can't see your movement code I'm not sure what else can cause this problem, but this code has a pitfall which is this line :
myRigidbody.velocity = Vector2.up * jumpForce;
this line will put the velocity of the object 0 value at x axis and jumpForce value at y axis, so what ever you are doing (movement, running...) on the x axis it will stop and only can jump with jumpforce value at the y axis and vertically only, and this what happens for you because I assume you are using the same way to implement your movement code. so to avoid this pitfall you need to add force to the state of your object which keeps the movement dynamic rather than control it statically (which is a bad practice) :
myRigidbody.AddForce(Vector2.up * jumpForce);
check this for more information about AddForce : https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html
also if you can put your movement code so we can check it, or write for you another code. Good luck
Upvotes: 1
Reputation: 333
Since I don't know your movement code, I am just going to assume it's ok. There might be a problem with Character Controller's .isGrounded. Try to log it on the console and see what it returns while moving. It sometimes misbehaves. If that's the case, you can:
Upvotes: 0