Press key to move forward automatically

Is there any way to move the player forward for a short distance automatically when F key’s pressed?

For instance, When I press F key, my player move slowly towards for 30 distance.

I have this in my script:

Character.transform.Translate(Vector3.forward * MoveForward);

But when I press F key, the character just “JUMP” to the position in one step, I mean I want it to move gradually. Hope my explanation’s clear.

Thanks for any help

You need to apply time delta to it, this is the amount of time since the last update so it will give you smooth movement. It’s also a good idea to translate it in the world space. try this…

transform.Translate(0, Time.deltaTime, 0, Space.World);

Will make your object move up and 1/unit per second.

EDIT: Make sure you have a rigidbody and collider applied to your character. If you’re using a character controller this should be done differently so let me know if that’s the case.

I would define the total distance and the desired velocity as variables like:

(javascript)

var distanceToGo: float;
var velocity: float = 1.0f;

When the F key is pressed set the distanceToGo variable to the desired total distance:

distanceToGo = 30; //(or maybe  +=30)

Then increment the position of the transform and decrement the distance to go by the velocity amount:

if (distanceToGo > 0)
{ 
   float normalizedVelocity = velocity*Time.deltaTime; //move the same speed regardless of frame rate
   Character.transform.Translate(Vector3.forward*normalizedVelocity );
   distanceToGo -=normalizedVelocity ;
}

Hope it helps! If it moves to fast or slow, just adjust the velocity setting.