# ,I am trying to code a dash in c#. I cant get it, help!

I have been trying for many days now to get a dash to work diagonally. I have consulted google to no avail and then I remembered Unity has a forum :). Hoping I can get some help (sorry if this is super easy I’m just beginning.

``````if (direction == 0)
{
if (Input.GetKey(KeyCode.A) & Input.GetKeyDown(KeyCode.Space) & hasDashed == false)

{
direction = 1;
hasDashed = true;

}
else if (Input.GetKey(KeyCode.D) & Input.GetKeyDown(KeyCode.Space) & hasDashed == false)
{
direction = 2;
hasDashed = true;
}
else if (Input.GetKey(KeyCode.W) & Input.GetKeyDown(KeyCode.Space) & hasDashed == false)
{
direction = 3;
hasDashed = true;
}
else if (Input.GetKey(KeyCode.S) & Input.GetKeyDown(KeyCode.Space) & hasDashed == false)
{
direction = 4;
hasDashed = true;

}

}
else
{
if (dashTime <= 0)
{
direction = 0;
dashTime = startDashTime;
rb.velocity = Vector2.zero;
}
else
{
dashTime -= Time.deltaTime;
if(direction == 1)
{
rb.velocity = Vector2.left * dashSpeed;
}
else if (direction == 2)
{
rb.velocity = Vector2.right * dashSpeed;
}
else if (direction == 3)
{
rb.velocity = Vector2.up * dashSpeed;
}
else if (direction == 4)
{
rb.velocity = Vector2.down * dashSpeed;
}

}
``````

I based this off a tutorial I found online. I hope it’s semi-coherent.

Thanks for any help in advance,

Gray

If your code repeats itself with slight variations, it’s usually a sign that things could be done better:

``````Vector2 dashVelocity = new Vector2();
dashVelocity.x = Mathf.Round(Input.GetAxisRaw("Horizontal"));
dashVelocity.y = Mathf.Round(Input.GetAxisRaw("Vertical"));

if (dashVelocity == Vector2.zero)
return;

dashVelocity *= dashSpeed;
``````

GetAxisRaw will use the controls defined in the Input panel. You can create more axis if you want. The difference with GetAxis is that it will not try to interpolate the value when it changes.

Round will force the axis to take the value of -1, 0 or 1. This means that there are 9 possible combinations, 1 for each direction, and 1 for not moving.

We can then check that the player is pressing directions keys during the dash or not by comparing the results to a zero vector. This is not ideal, as you shouldn’t usually compare floats using an equal sign, but it’s short.