find the damage sourcecan be a non-player entity when player is attack in minecraftusing datapck
In Minecraft, you can use a datapack to detect the damage source when a player is attacked, even if the damage is caused by a non-player entity. Here's an example of how you can achieve this:
-
Create a new datapack for your Minecraft world. You can do this by creating a new folder inside the
datapacksfolder of your Minecraft world's save folder. Name the folder something descriptive, likeDamageSource. -
Inside the
DamageSourcefolder, create the following directory structure:
DamageSource
└── data
└── minecraft
└── tags
└── functions
-
Create a new file inside the
functionsfolder and name itdetect_damage.mcfunction. This will be the function that detects the damage source. -
Open the
detect_damage.mcfunctionfile and add the following commands:
execute as @a[scores={attack=1..}] at @s store result entity @s LastDamageSourceTag string 1 run execute at @s run data get entity @s attacking_entity
scoreboard players reset @a attack
Let's break down what each command does:
execute as @a[scores={attack=1..}]: This command executes the following commands as all players who have a score ofattackequal to or greater than 1.at @s: This command sets the execution position to the current player's position.store result entity @s LastDamageSourceTag string 1 run execute at @s run data get entity @s attacking_entity: This command stores theattacking_entitytag of the current player in theirLastDamageSourceTagscoreboard tag. It uses thedata getcommand to retrieve the tag value.scoreboard players reset @a attack: This command resets theattackscore for all players.
-
Save the
detect_damage.mcfunctionfile. -
Now, you need to enable the datapack in your Minecraft world. Start or reload your world and run the following command in the chat:
/datapack enable "file/DamageSource"
Make sure to replace "file/DamageSource" with the actual path to your datapack folder.
- To use the datapack, you need to give players a score of
1for theattackobjective whenever they are attacked. You can achieve this using various methods, such as a repeating command block or a function. For example, you can run the following command in a repeating command block:
execute as @a[scores={attack=0}] at @s if entity @s[distance=0..1] run scoreboard players add @s attack 1
Now, whenever a player is attacked by any entity, including non-player entities like mobs, the LastDamageSourceTag of the player will be updated with the tag of the attacking entity. You can then use this information in other functions or commands to react accordingly
原文地址: https://www.cveoy.top/t/topic/h6kc 著作权归作者所有。请勿转载和采集!