jump through platform causes double jump
I'm making simple 2D sidescrolling game and i wanted my character to jump through some platforms. I used platform effector for this and that works but causes some problem. If i press jump when my character is in platform, he jumps again but on very long distance. I don't know how to fix this. Is there anyway without copletely rebuilding collisions?
Here is my jump function:
if (IsGround() && Input.GetKeyDown(KeyCode.Space))
{
RgBody.AddForce(new Vector2(0f, JumpForce)); // dodanie sił
anim.SetTrigger("jump");
}
And here is IsGround() function:
private bool IsGround()
{
RaycastHit2D raycastHit2D = Physics2D.BoxCast(circleCollider2D.bounds.center, circleCollider2D.bounds.size, 0f, Vector2.down, .1f,layerMask);
return raycastHit2D.collider != null;
}
Answer by lgarczyn · Dec 09, 2019 at 02:15 AM
Change this:
RaycastHit2D raycastHit2D = Physics2D.BoxCast(circleCollider2D.bounds.center, circleCollider2D.bounds.size, 0f, Vector2.down, .1f,layerMask);
to this:
RaycastHit2D raycastHit2D = Physics2D.BoxCast(
circleCollider2D.bounds.min + 0.01f * Vector2.up,
circleCollider2D.bounds.size,
0f, Vector2.down, .05f,layerMask);
That way, being halfway through a collider won't allow you to jump. You can also reduce the length of the raycast further to prevent jump firing twice.
You can also make this slightly better by adding a delay between two jumps, like this:
void FixedUpdate()
{
if (Input.GetKey(KeyCode.Space) && IsGround && jumpTimer <= 0f)
{
//jump
jumpTimer = 0.5f; //maximum delay in seconds between two jumps
}
jumpTimer -= Time.fixedDeltaTime;
}
Perhaps a more elegant solution is to only allow a jump if it doesn't increase your velocity past the standard jumping velocity.
That would be:
if (velocity.y < jumpSpeed)
velocity.y = jumpSpeed;
This would allow you to get rid of the timer.
With your raycastHit i've got that error: error CS0019: Operator '*' cannot be applied to operands of type 'double' and 'Vector2'
if i delete "0.01 * Vector2.up" from second line it works but double jump still occurs but less.
Sorry, you need to write 0.01f ins$$anonymous$$d of 0.01.
Your answer
Follow this Question
Related Questions
Help me in 2d Plataform game, walking in wall 0 Answers
Collider2D of game object does not work, unless I duplicate the game object. 1 Answer
Compatible collision constraint methods 0 Answers
Error: An object reference is required to access non-static member, help? 2 Answers
Unty 3D C# Load other scene when bool = true, otherwise perform teleportation as commanded. 1 Answer