Count Taps per second

Hi guys im trying to implement character speed into my game by determining the amount of taps per second the user does.

Since i cant find anything i could i put together at the docs i went to google it and only found 1 result.

private List<float> taps = new List<float> ();
public float tapsPerSecond;
 
void Update () {
    if (<tap touch idk, but u know>) {
        taps.Add(Time.timeSinceLevelLoad);
    }
    for (int i = 0, i < taps.Count; i++) {
        if (taps *<= Time.timeSinceLevelLoad-1) {*

taps.Remove(i);
}
}
tapsPerSecond = taps.Count;
}
Could someone help me explain this script to me or help me make a simple script that i could work with.I will try to help as much as i can.Thanks

To start with, replace line 5 with:

 if (Input.GetMouseButtonUp(0)) {

Now you can play with this code in the Editor. For basic use in touch, you can replace this line by:

  if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Ended)) {

But this line does not handle multiple touches. It does not distinguish between a tap, a press, or a swipe. So how much additional work you need to do will depend on 1) your definition of touch, and 2) how you want to deal with multiple touches.

As for how this code works, each time it detects a touch, it puts the time of that touch in a list. Lines 8 through 12 comb through that list and remove any that are over one second old. The count of the remaining entries in the list will be the touches per second.

Here is your code modified to handle multiple touches, but it does not distinguish between tap, press, swipe, etc.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

class Example : MonoBehaviour {
	private List<float> taps = new List<float> ();
	public float tapsPerSecond;
	
	void Update () {
		foreach (Touch touch in Input.touches) {
			if (touch.phase == TouchPhase.Ended)
				taps.Add(Time.timeSinceLevelLoad);
		}
		for (int i = 0; i < taps.Count; i++) {
			if (taps *<= Time.timeSinceLevelLoad-1) {*
  •  		taps.Remove(i);*
    
  •  	}*
    
  •  }*
    
  • tapsPerSecond = taps.Count;*
  • }*
    }
    To distinguish between tap, press, swipe, etc. would require data structures that tracked the fingerId of the touches and saved the position and time of events.
    Also your original code has a bug in the for() line where a ‘,’ should be a ‘;’.

You could set up that when 1 tap is entered then a yield for seconds is activated and then have the amount of taps = the amount of speed, but if you don’t tap fast enough then you will go back to average speed.

I hope this helps :slight_smile:

I know most people are looking for a script themselves but with this information it would be fun to test out your own scripts and use mono develop to debug it. It sounds a little complicated but I think it’s worth a shot for you.