Minecraft – (Java Minecraft 1.14.3) How to detect a player holding right click

minecraft-commandsminecraft-java-edition

I would like to run a function whenever a player is charging a bow, essentially using the bow as a held right click detector. I thought to use SelectedItem and some nbt tag to do this, but the wiki page for player.dat format doesn't mention bows, just crossbows, and only in terms of what projectile it is charged with. I'm not sure SelectedItem could work for this, but if it can that would be great. I know the command will be something like this:

execute as @a[nbt={SelectedItem:{"id":"minecraft:bow",tag:{?}}}] at @s run function namespace:function

Edit:

Any way of detecting a hold and click would be a good answer if using SelectedItem is impossible.

Best Answer

You can't detect a right click with a bow, you can however use a carrot on a stick.

This would require 2 scoreboard objectives, one to detect when a carrot on a stick is used and one dummy objective that you can use as timer, because the carrot on the stick will only be used every 4-5 ticks:

/scoreboard objectives add carrots minecraft.used:minecraft.carrot_on_a_stick
/scoreboard objectives add timer dummy

You would then repeatedly have to run these commands in this order, in your case probably in a function:

#count the timer down
scoreboard players remove @a[scores={timer=1..}] timer 1

#reset the timer if the carrot on the stick was used
scoreboard players set @a[scores={carrots=1}] timer 5

#reset the scoreboard that detects if the carrot on the stick was used
scoreboard players set @a carrots 0

The timer will never reach 0 as long as the player holds right click, so your command would look like this:

execute as @a[scores={timer=1..}] at @s run function namespace:function

This will have a delay of a bit less than 5 ticks (0.25 seconds) after the player releases the right click, so it is possible to detect a right click even if the player already released it for a short period of time.

Use this command to give yourself a carrot on a stick that doesn't break:

/give @s minecraft:carrot_on_a_stick{Unbreakable:1}