- Home /
Double Tap Not Working
I have been trying to get my character to walk when the W button is pressed and run when the same button is tapped twice between a certain time period (eg. 0.5s). I have two animations which I want to play, run and walk however only the walk animation is played and the transform function that is used to move my character does not seem to work.
Here is the script I am using:
var walkSpeed = 1.5;
var runSpeed = 15;
var backwardsWalkSpeed = 0.75;
var rotateSpeed = 2;
private var lastTapTime = 0;
var tapSpeed = 0.5;
function Update ()
{
if(Input.GetKeyDown(KeyCode.W))
{
if ((Time.time - lastTapTime) < tapSpeed)
{
animation.CrossFade("Run");
transform.position += transform.forward * runSpeed * Time.deltaTime;
}
if ((Time.time - lastTapTime) > tapSpeed)
{
animation.CrossFade("Walk");
transform.position += transform.forward * walkSpeed * Time.deltaTime;
}
lastTapTime = Time.time;
}
if(Input.GetKeyUp(KeyCode.W))
{
animation.CrossFade("Idle");
}
if(Input.GetKeyDown(KeyCode.S))
{
animation.CrossFade("Walk");
animation["Walk"].speed = 0.5;
}
if(Input.GetKeyUp(KeyCode.S))
{
animation.CrossFade("Idle");
animation["Walk"].speed = 1;
}
if(Input.GetKey(KeyCode.S))
{
transform.position += -transform.forward * backwardsWalkSpeed * Time.deltaTime;
}
}
Like I said previously, I can only get the walk animation to work, and neither the transform function for the walk/run or the run animation. Any help would be much appreciated!
Answer by mpavlinsky · Jan 05, 2012 at 01:13 PM
GetKeyDown() only returns true on the first frame the key is pressed, so you'll only be moving for that single frame. This should still move you very slightly, you can check the transform data in the editor to confirm that.
Seems like you had the right idea with the backing up. For the running I think you want to do something similar with GetKey() like:
bool running = false;
if(Input.GetKeyDown(KeyCode.W))
{
if ((Time.time - lastTapTime) < tapSpeed)
{
runnning = true;
animation.CrossFade("Run");
}
else
{
running = false;
animation.CrossFade("Walk");
}
lastTapTime = Time.time;
}
if (Input.GetKey(KeyCode.W))
{
transform.position += transform.forward * (running ? runSpeed : walkSpeed) * Time.deltaTime;
}
if (Input.GetKeyUp(KeyCode.W))
{
running = false;
animation.CrossFade("Idle");
}
Great! I managed to fix the first issue which was quite stupid actually. I just extended the double tap time and it worked perfect. Also, I used a very similar script as yours and again worked well. Thanx for the help! :D
Your answer
