'Unity 2D platform game Dashing using inputSystem
I am making a 2D platform game similar to Megaman X/Zero with unity as my side project, and I am trying to implement the dash function.
Following a course on Udemy, now I can make the Player jump,run and shoot bullets, but I can't make it dash.
I used InputSystem to make moves, here is my code:
void OnJump(InputValue value) //OnJump() is automatically recognized by unity, which will run when the jump button was pressed
{
//if it is pressed and also the capsulecollider of the player is touching Groundlayer(is on ground)
//then add velocity to y so it can jump ONCE
if (value.isPressed && myCapsuleCollider.IsTouchingLayers(LayerMask.GetMask("Ground")))
{
myRigid.velocity += new Vector2(0f,jumpSpeed);
}
}
void OnDash(InputValue value)
{
if (value.isPressed)
{
myRigid.velocity += new Vector2(dashSpeed,0f );
}
}
The way I am thinking is: If I can successfully make the player Jump by adding velocity on y-axis, why can't I make it dash using the same way? just add velocity towards another direction?
Solution 1:[1]
Jumping works because the rigid body will take care of gravity and apply it for you, resulting in the character falling down, dashing is different, there is no opposite force to decrease the velocity and therefore your character will only speed up when you try dashing. The correct implementation should disable input when dashing and to revert the added velocity when it's done. You can implement that best using a coroutine. The example below applies a speed boost temporarily, it does not disable the input tho:
private bool isDashing = false;
IEnumerator DashCoroutine(int dashDuration)
{
if(isDashing)
yield break;
isDashing = true;
myRigid.velocity = new Vector(dashSpeed,0);
yield return new WaitForSeconds(dashDuration);
myRigid.velocity = new Vector(0,0);
isDashing = false;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
