My dash script only works occasionally but I’m not sure what I’m doing wrong. I want the player character to be able to dash when double pressing a movement key.
using UnityEngine;
public class DashScript : MonoBehaviour
{
float dashTimer, dashInterval;
KeyCode firstKey, secondKey, currentKey;
bool firstKeyHit, secondKeyHit, dashed;
void Start()
{
dashTimer = 0.2f;
dashInterval = dashTimer;
firstKeyHit = false;
dashed = false;
secondKeyHit = false;
firstKey = KeyCode.None;
secondKey = KeyCode.None;
}
void Update()
{
if(!firstKeyHit)
{
currentKey = GetKey();
}
if (Input.GetKeyUp(currentKey) && currentKey != KeyCode.None)
{
firstKey = GetKey();
firstKeyHit = true;
}
GetSecondKey();
Compare();
Timer();
}
//Compares the two keys and sets the new position accordingly
private void Compare()
{
if(firstKey == secondKey && !dashed && firstKey != KeyCode.None)
{
Debug.Log("In the compare method");
Vector3 newPos =
secondKey == KeyCode.W ? gameObject.transform.forward :
(secondKey == KeyCode.S ? -gameObject.transform.forward :
(secondKey == KeyCode.D ? gameObject.transform.right :
(secondKey == KeyCode.A ? -gameObject.transform.right : Vector3.zero)));
Debug.Log(firstKey.ToString() + secondKey.ToString());
gameObject.GetComponent<CharacterController>().Move(newPos * 10);
firstKey = KeyCode.None;
secondKey = KeyCode.None;
dashed = true;
}
}
//Timer window for a doublepress
private void Timer()
{
if (firstKeyHit)
{
dashTimer -= Time.deltaTime;
if(dashTimer < 0)
{
dashTimer = dashInterval;
dashed = false;
firstKeyHit = false;
secondKeyHit = false;
currentKey = KeyCode.None;
}
}
}
//Gets the second key value
private void GetSecondKey()
{
if(firstKeyHit)
{
secondKey = GetKey();
secondKeyHit = true;
}
}
//Gets the key value pressed
private KeyCode GetKey()
{
KeyCode returnValue = KeyCode.None;
if(Input.GetKey(KeyCode.W))
{
returnValue = KeyCode.W;
}
else if(Input.GetKeyDown(KeyCode.S))
{
returnValue = KeyCode.S;
}
else if( Input.GetKeyDown(KeyCode.A))
{
returnValue = KeyCode.A;
}
else if(Input.GetKeyDown(KeyCode.D))
{
returnValue = KeyCode.D;
}
return returnValue;
}
}
Any help appreciated!