How to kill an Entity a Player is looking at?

  • Is there a command that would kill the entity that the player is looking at?

  • QA Engineer

    This is another question involving raycasting.

    To perform raycasting you need a datapack. For how to set up a Minecraft Datapack, look for tutorials made by Cloudwolf, Legitimoose and the likes.

    In the datapack functions folder, you want a function called raycast.mcfunction

    In the function,

    tag @s add this
    execute if entity @e[tag=!this,distance=0..0.99] run kill @e[sort=nearest,limit=1,tag=!this]
    tag @s remove this
    execute if block ~ ~ ~ air positioned ^ ^ ^0.2 run function namespace:raycast
    execute if block ~ ~ ~ cave_air positioned ^ ^ ^0.2 run function namespace:raycast

    After you put the above code into your function, you simply need to call the function from your tick function or in the game using a repeating command block. Something like this would be useful : execute as PlayerName at @s positioned ~ ~1.6 ~ run function namespace:raycast

    Go into the game and slash reload. To this point you should notice that whatever your crosshair points at will die immediately. How it works is that you are creating a recursive function (a function that calls itself) that runs itself across the 3D MInecraft World and everytime the function catches an entity in its way within a 0.99 meter proximity you will kill that entity. The player itself however is immune from this effect because of the tagging command which allows the function to always exclude the command initator while trying to kill the closest entity.

    Another thing is that there are countless entities in Minecraft. The popular belief is that only Mobs like Zombies and Creepers are entities which is very wrong. Arrows, armor stands, area effect clouds, markers, minecarts, paintings etc. actually makes up for a larger percentage of the total entity count in Minecraft. If you don't wish to gaze at your painting and watch as it disappears, you should define an entity group called #exclude which you can add to the kill selector to neglect unimportant entities.

    Here is a .json file I use for #exclude.


    Hope this helps. I can provide you with a sample datapack in case something goes wrong.

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2