Dash! a-ah Savior of the Universe

Ball Star Battle is a project that I'm primarily trying to simply improve my coding practices with. I'm attempting to use more coding patterns more effectively, I'm trying to do more in less lines and I'm trying stuff that I'm ju7st not used to yet.

On of these techniques that I'm not used to a coroutine. For Ball Star Battle, characters must be able to dash, and at first, I believed that it would be rather simple for me to increase the movement speed of the character, or add force in a particular direction. Which is, shamefully, what I did initially do. Trying to come up for a better way of implementing dashing, I came across the use of coroutines, which I haven't used in practice before.

IEnumerator dash(Vector3 direction) 
     { 
         myState = PlayerStates.psDashing; 
        Vector3 startPos = transform.position; 
        Vector3 tarPos = startPos + (direction * moveSettings.dashDist);  
        int dashDuration = (int)(moveSettings.dashDist / moveSettings.dashSpeed);  
         for (int f = 0; f < dashDuration; f++) 
        { 
            if(myState != CharacterController.PlayerStates.psDashing){ 
            yield break; 
                 myState = PlayerStates.psDashRecovery; 
            }  
            transform.position = Vector3.Lerp(startPos, tarPos, moveSettings.dashAniCurve.Evaluate((float)f / dashDuration)); 
           yield return null; 
        } 
        myState = PlayerStates.psDashRecovery; 
    } 
} 

This IEnumerator is named dash, and takes a Vector3 Direction as an argument. This IEnumerator will be invoked when the player presses the dash button, and is not already dashing, or recovering from formerly doing so. The dash direction is calculated before the IEnumerator is invoked, by finding the direction that the player is trying to dash in. The IEnumarator finds the target position, and lerps between them over a set number of frames.

By passing information through an animation curve, I've found that modifying the speed of the dash is extremely easy, and modifying the variables used in this script enables other components in the script to alter the speed or distance that the character can dash. In general, this block of code has saved me a lot of time putting out other areas of the tyre fire that is the rest of this game, and I can leave it alone knowing that it will definitely do what I want it to do.

 

Tylah Kapa