- Home /
Double Tap to Run
I basically want to double tap the arrow/a/d key to make my character run instead of walk. I have no clue how to even begin doing this, so I'm asking for someone to either do it for me or give me an example I can embellish on.
Originally, walkspeed = 30, I want it to be 50 when I double tap.
function Update () {
if(grounded) {
moveDirection = new Vector3(0,0,Input.GetAxis("Horizontal"));
transform.LookAt(transform.position + moveDirection);
if(isMoveable == true && !isAttacking){
moveDirection *= walkSpeed;
}
if(moveDirection != Vector3.zero && isMoveable && !isAttacking){
if (Time.time - lastTime < 0.2f){
lastTime = Time.time;
walkSpeed = 30;
animation.CrossFade("run",0.1);
isMoving = true;
}else{
lastTime = Time.time;
walkSpeed = 50;
animation.CrossFade("run",0.1);
isMoving = true;
}
} else {
isMoving = false;
if(!lookingUp){
animation.CrossFade("Take 001",0.1);
}
if(lookingUp){
animation.CrossFade("idleUp",0.1);
}
}
if(Input.GetButton("Jump") && !isJumping && !isShooting && !isAttacking) {
Jump();
}
}
I would suggest starting a timer when you hit the arrow-key and if the timer is less than (let us say .50 seconds(half a second)) then make the character run.
Answer by TheDemiurge · Apr 09, 2011 at 07:33 AM
I'm assuming you plan to have the key held down for both walking and running. The following is based on that assumption. The easiest way to do this is by checking how much time has passed since the last time we hit a certain key to run. You'll probably want to keep a KeyCode type variable, which makes it easy to change which key you want for walk/run, but if you're hard coding a key that works as well. Whenever the key is tapped, you do a check of the "current time minus last time" sort. If this time frame is smaller than X, the key has been double-tapped. Regardless, also set last time to current time.
Something like the following:
// var walkKey: KeyCode = KeyCode.D;
// var lastTime: float = -1.0f;
if (Input.GetKeyDown(walkKey))
{
if (Time.time - lastTime < 0.2f)
{
lastTime = Time.time;
// turn on running
} else
{
lastTime = Time.time;
// turn on (or switch to) walking
}
}
if (!Input.GetAxis("Horizontal"))
{
/* the key is no longer being held */
// make the character stop moving
}
Something roughly like that would do the trick. How you actually set the walking/running is up to you. For added control or different playstyles you can mess around with a particular input axis' Gravity and Sensitivity fields. Check out Unity's Input Manager for more on that.
Alright I updated the first post with my new code but it doesn't seem to be working. If I double tap the walkspeed doesn't increase at all, and the lastTime var doesn't reset after I let go.
I've been running into the same problem and I couldn't figure out how to get around it. I assume it has something to do with Time.time not resetting itself after every press. How did you finally get it to work?