How to teleport a player upwards every two seconds? [duplicate]

I want to make a setup with command blocks that will, if you hold a specific item, elevate you 100 blocks. For example, when you hold an ender pearl named "Sky Orb", you would be teleported 100 blocks up each couple of seconds. I already have the necessary commands:

/scoreboard objectives add Holding dummy
/scoreboard players set @a Holding 0
/scoreboard players set @a Holding 1 {SelectedItem:{id:"minecraft:ender_pearl",tag:{display:{Name:"Sky Orb"}}}}
/tp @a[score_Holding_min=1] ~ ~100 ~ 

Basically, the main problem is the delay. You should only be teleported every 2 seconds or so. Does anyone know a setup for this?

(I'm using the 1.9 snapshots)


Solution 1:

This can be done by doing some additions to your commands, and introducing a scoreboard operation:

/scoreboard objectives add Holding dummy
/scoreboard objectives add flyTimer dummy
/scoreboard players set #MATH flyTimer 40

/scoreboard players set @a Holding 0
/scoreboard players set @a Holding 1 {SelectedItem:{id:"minecraft:ender_pearl",tag:{display:{Name:"Sky Orb"}}}}
/scoreboard players set @a[score_Holding=0] flyTimer 0
/scoreboard players add @a[score_Holding_min=1] flyTimer 1
/scoreboard players operation @a flyTimer %= #MATH flyTimer 
/tp @a[score_flyTimer_min=10,score_flyTimer=10] ~ ~100 ~

First, we add another score called flyTimer and set its score of a nonexistent player called #MATH to 40. The hash character ensures that this can never be a real player, and it will also not show up if you set the scoreboard display to sidebar.

We use the holding score to increase the timer. This decoupling is necessary because we can "negate" scores in a target selector but not in data tags. I.e. we need it to be able to target players not holding the ender pearl. Note that the flyTimer will reset immediately when swapping to another item.

After the score is increased, we perform a modulo operation on it, using the score of our #MATH dummy. This means that the score is reset to 0 whenever it reaches 40, i.e. every 2 seconds (for other timings, change the score of the #MATH dummy accordingly).

Lastly, we make it so that the teleport command is only executed when the score is exactly 10. This number controls the delay of the teleport after selecting the item in your hotbar. You can tweak this number to suit your needs.