Jump to content

[1.16.5] Raytrace Block Position and Summon Lightning


jaxbymc42

Recommended Posts

Hello!  I am looking to use ray tracing to find the position of the block the player is looking at.  Then, when the player right clicks the item, it summons a lightning bolt at that block's location.  I have created my own code for this, but nothing is currently working (not summoning lightning at all).  I am new to ray tracing but apparently this is not how it is done (question mark?).  I am just looking to see what I have done wrong and to build on knowledge for the future.

 

import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.effect.LightningBoltEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.stats.Stats;
import net.minecraft.util.ActionResult;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.EntityRayTraceResult;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.RayTraceContext;
import net.minecraft.util.math.RayTraceContext.FluidMode;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;

public class LightningWandItem extends Item
{
	public LightningWandItem(Properties properties) 
	{
		super(properties);
	}

	private RayTraceResult rayTrace(World world, PlayerEntity player)
	{
		float rotationPitch = player.getYHeadRot();
		float rotationYaw = player.xRot;
		Vector3d eyePosition = player.getEyePosition(1.0F);
		
		// look vector
		float f2 = MathHelper.cos(-rotationYaw * ((float)Math.PI / 180F) - (float)Math.PI);
		float f3 = MathHelper.sin(-rotationYaw * ((float)Math.PI / 180F) - (float)Math.PI);
		float f4 = -MathHelper.cos(-rotationPitch * ((float)Math.PI / 180F));
		float f5 = MathHelper.sin(-rotationPitch * ((float)Math.PI / 180F));
		float f6 = f3 * f4;
		float f7 = f2 * f4;
		double rayTraceDistance = 54;
		
		// from start pos, add look vector multiplied by rayTraceDistance
		Vector3d endPosition = eyePosition.add((double)f6 * rayTraceDistance, (double)f5 * rayTraceDistance, (double)f7 * rayTraceDistance);
		return world.clip(new RayTraceContext(eyePosition, endPosition, RayTraceContext.BlockMode.OUTLINE, FluidMode.NONE, player));
	}
	
	public ActionResult<ItemStack> onItemRightClick(World worldIn, PlayerEntity playerIn, Hand handIn) 
	{
		if(!worldIn.isClientSide)
		{
			ItemStack stack = playerIn.getItemInHand(handIn);
			RayTraceResult result = this.rayTrace(worldIn, playerIn);
			if(result instanceof BlockRayTraceResult)
			{
				BlockPos pos = ((BlockRayTraceResult) result).getBlockPos();
				Block block = worldIn.getBlockState(pos).getBlock();
				if(block != Blocks.AIR)
				{
					if(worldIn instanceof ServerWorld)
					{
						LightningBoltEntity lightningEntity = new LightningBoltEntity(EntityType.LIGHTNING_BOLT, worldIn);
						lightningEntity.setPos(pos.getX(), pos.getY(), pos.getZ());
						
						playerIn.awardStat(Stats.ITEM_USED.get(this));
						if (!playerIn.abilities.mayfly) {
							stack.hurtAndBreak(1, playerIn, (p_219998_1_) -> {
								p_219998_1_.broadcastBreakEvent(handIn);
							});
						}	
					}
				}
				return new ActionResult<ItemStack>(ActionResultType.SUCCESS, stack);
				
			} else if(result instanceof EntityRayTraceResult)
			{
				Entity entity = ((EntityRayTraceResult) result).getEntity();
				if(worldIn instanceof ServerWorld)
				{
					Vector3d entityPos = entity.position();
					LightningBoltEntity lightningEntity = new LightningBoltEntity(EntityType.LIGHTNING_BOLT, worldIn);
					lightningEntity.setPos(entityPos.x(), entityPos.y(), entityPos.z());
				
					playerIn.awardStat(Stats.ITEM_USED.get(this));
					if (!playerIn.abilities.mayfly) {
						stack.hurtAndBreak(1, playerIn, (p_219998_1_) -> {
							p_219998_1_.broadcastBreakEvent(handIn);
						});
					}
				}
				return new ActionResult<ItemStack>(ActionResultType.SUCCESS, stack);
			}
			
			playerIn.getItemInHand(handIn);
		}
		return super.use(worldIn, playerIn, handIn);
	}
}

 

Link to comment
Share on other sites

I do now realize that I wasn't using the correct method.  I have changed "onItemRightClick" to "use" and now the item does function.  It functions because I also added the entity to the world, as you had mentioned that I had not added it (oops).  Now, it does summon lightning, but only whenever I look certain ways and my ray tracing does not work well because the lightning is not summoned where I am looking.  I will try to use getLookVec (or whatever the name is) to trace instead and see how that goes.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • What MC version? What's the IP? Are any mods needed to be able to join?
    • Thank you for your answer ! Unfortunatly i have the same problem when i use setPos() public static int movingfunction(CommandContext<CommandSourceStack> context){ CommandSourceStack source = context.getSource(); if (!(source.getEntity() instanceof ServerPlayer)) { return 0; } ServerPlayer player = (ServerPlayer ) source.getEntity(); double moveSpeed = 0.5; for (int i =0; i<10000;i++) { LOGGER.info("running for the {} time", i); double x = player.getX() + player.getViewVector(1.0f).x * moveSpeed; double y = player.getY(); double z = player.getZ() + player.getViewVector(1.0f).z * moveSpeed ; Vec3 movementVec = new Vec3(x, y, z); LOGGER.info("x ={} y ={} z ={}", x, y, z); player.setPos( movementVec); } return 1; } With the logs i can see that x and z are increasing but once again my player is not moving. is there a function to use to sync the server and the client ? I also tried to use LocalPlayer instead of ServerPlayer but my code would stop when i got the object. Also i will change a bit the main topic but is there a way to similate key press ? i found KeyBinding.setKeyBindState on others post but it look like there is no more KeyBinding in 1.20   I found this code : KeyMapping.click(Minecraft.getInstance().options.keyUp.getKey()); But it doesn't seems to work   And i found this one : Minecraft.getInstance().options.keyUp.setDown(true); wich works but doesn't exactly do what i want , it doesn't release the key so for exemple i can't make him run. Minecraft.getInstance().options.keyUp.setDown(true); Minecraft.getInstance().options.keyUp.setDown(false); Minecraft.getInstance().options.keyUp.setDown(true); doesn't make him run
    • Add crash-reports with sites like https://paste.ee/ Maybe an issue with blur, essentials or cumulus_menus
    • Add the crash-report or latest.log (logs-folder) with sites like https://paste.ee/ and paste the link to it here  
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.