- Home /
Detect Frecuency/Speed of Pressing a Button
Hi, for a racing game I'm working on, I had the idea of making a game mode in which you have to press as fast as you can a button to make the car go faster and win. But how could I detect the speed in which the player is pressing a button?
Answer by robertbu · Mar 23, 2013 at 01:04 AM
To solve this problem, you don't need to calculate button frequency. Instead make each button press add just a bit of force/speed So if you are using a Rigidbody, you could do something like:
if (Input.GetKeyDown(KeyCode.Space))
rigidbody.AddForce(transform.forward * small_force * Time.deltaTime);
If you are moving your car through Transform.translate(), use a speed variable. Each time they press the button, increase the speed variable just a bit.
if (Input.GetKeyDown(KeyCode.Space))
speed += small_value;
transform.Translate(transform.forward * speed * Time.deltaTime);
Thanks, it is working, but now I would like that the speed decrease s if you don't press the button, any ideas?
If you are using a Rigidbody, you can do one or more of the following:
In the inspector, increase drag for the Rigidbody
Change the properties of the Physic material for both the car and the surface for the Rigidbodies.
Add a small amount of counter force each frame. That is:
rigidbody.AddForce(-transform.forward very_small_force Time.deltaTime);
If you are using translation, you can multiply the speed value by a friction value just under 1.0. Something like:
speed *= 0.975;
Note that both of these would happen every frame, and the other forces would only be added/changed on the press of a key. It might take some playing to get the right balance.
Answer by BPR · Mar 22, 2013 at 10:31 PM
Hi, try to save the current time with
float startT =time.time;
then count the amout of button presses by increasing an integer for each time the buttion is pressed
if (Input.getKeyDown(...)){
count++;
}
then when you want to evaluate the frequency store the current time
float endT = time.time;
then subtract the start time from the end time and divide the number of button pushes through the result
float frequency = count / (endT-startT);
Regards, BPR
Hi, thanks for the quick response, but how could I write it fot java? Float = Var?
Yes, in javascript it's automatically chosen so float = var
Your answer
Follow this Question
Related Questions
Making a button in unity iphone? 3 Answers
How to change pace by pressing different buttons once? 1 Answer
Detect Mouse Click OnGUI 1 Answer
How to change UI button animation speed (4.6 UI) 2 Answers
Press Any Key To Continue 0 Answers