Jump to content

[1.16.5] Player.attack not working with EntityRayTraceResult


TheDerpyParagon

Recommended Posts

I am creating a mod in which I need to extend the attack reach of the player without the player using an item like a sword. I got an amazing EntityRayTraceResult variable from someone on the forums, and that is what you can see in the middle of my code. The RayTraceResult gets the entity successfully, and it is printed in the console, but I am having trouble getting the player to actually attack the entity.

@EventBusSubscriber(modid = TitanShiftersMod.MOD_ID, bus = Bus.FORGE)
public class EntityReachExtender {
	
	private static double range;
	
	public static void setEntityRange(double r) {
		range = r * 80;
	}
	
	public static double getEntityRange() {
		return range;
	}
	
	public static EntityRayTraceResult getPlayerPOVHitResult(PlayerEntity player) {
		  float playerRotX = player.xRot;
		  float playerRotY = player.yRot;
		  Vector3d startPos = player.getEyePosition(1);
		  float f2 = (float) Math.cos(-playerRotY * ((float)Math.PI / 180F) - (float)Math.PI);
		  float f3 = (float) Math.sin(-playerRotY * ((float)Math.PI / 180F) - (float)Math.PI);
		  float f4 = (float) -Math.cos(-playerRotX * ((float)Math.PI / 180F));
		  float additionY = (float) Math.sin(-playerRotX * ((float)Math.PI / 180F));
		  float additionX = f3 * f4;
		  float additionZ = f2 * f4;
		  double d0 = range;
		  Vector3d endVec = startPos.add((double)additionX * d0, (double)additionY * d0, (double)additionZ * d0);
		  AxisAlignedBB startEndBox = new AxisAlignedBB(startPos, endVec);
		  Entity entity = null;
		  for(Entity entity1 : player.level.getEntities(player, startEndBox, (val) -> true)) {
			AxisAlignedBB aabb = entity1.getBoundingBox().inflate(entity1.getPickRadius());
			Optional<Vector3d> optional = aabb.clip(startPos, endVec);
		    if (aabb.contains(startPos)) {
		      if (d0 >= 0.0D) {
		        entity = entity1;
		        startPos = optional.orElse(startPos);
		        d0 = 0.0D;
		      }
		    } else if (optional.isPresent()) {
		      Vector3d vec31 = optional.get();
		      double d1 = startPos.distanceToSqr(vec31);
		      if (d1 < d0 || d0 == 0.0D) {
		        if (entity1.getRootVehicle() == player.getRootVehicle() && !entity1.canRiderInteract()) {
		          if (d0 == 0.0D) {
		            entity = entity1;
		            startPos = vec31;
		          }
		        } else {
		          entity = entity1;
		          startPos = vec31;
		          d0 = d1;
		        }
		      }
		    }
		  }

		  return (entity == null) ? null:new EntityRayTraceResult(entity);

	}
	
	@SubscribeEvent
	public void entityReach(LeftClickEmpty event) {
		
		LazyOptional<ITitanShifters> titan = event.getPlayer().getCapability(TitanShiftersProvider.TITAN_SHIFTERS_CAPABILITY, TitanShiftersMod.direction);
		ITitanShifters titanShifter = titan.orElse(new TitanShifters());
		
		EntityRayTraceResult t = getPlayerPOVHitResult(event.getPlayer());
		if(titanShifter.getPureTitan()) {
			if(t != null) {
				if(t.getEntity() != null) {
					System.out.println(t.getEntity());
					event.getPlayer().attack(t.getEntity());
				}
			}
		}
	}
}

The entity gets printed out successfully, but the entity does not get damaged. I have tried using a packet to make the player attack the entity on the server side, but that did not work. I got the same results as I am getting with this code.

Link to comment
Share on other sites

8 hours ago, poopoodice said:

Maybe something's wrong with your packet?

That's probably it. I've never used packets before, so I am not very familiar with how they work.

Here's my network:

public class TitanShiftersNetwork {

	public static final String NETWORK_VERSION = "0.1.0";
	
	public static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel(new ResourceLocation(TitanShiftersMod.MOD_ID, "network"),
			() -> NETWORK_VERSION, version -> version.equals(NETWORK_VERSION), version -> version.equals(NETWORK_VERSION));
	
	public static void init() {
		
		CHANNEL.registerMessage(0, InputMessage.class, InputMessage::encode, InputMessage::decode, InputMessage::handle);
		
	}
}

And here's my Input Message:

public class InputMessage {
	
	private static Entity entity;
	
	public InputMessage() {
		
	}
	
	public InputMessage(Entity e) {
		entity = e;
	}
	
	public static void encode(InputMessage message, PacketBuffer buffer) {
		
	}
	
	public static InputMessage decode(PacketBuffer buffer) {
		return new InputMessage(entity);
	}
	
	public static void handle(InputMessage message, Supplier<NetworkEvent.Context> contextSupplier) {
		NetworkEvent.Context context = contextSupplier.get();
		context.enqueueWork(() -> {
			
			ServerPlayerEntity player = context.getSender();
			
			player.attack(entity);
			
          	System.out.println("Working!");
		});
		context.setPacketHandled(true);
	}
}

And here's how I send a packet through to the server:

TitanShiftersNetwork.CHANNEL.sendToServer(new InputMessage(t.getEntity()));

This packet prints out the "Working!" line into the console, but does not attack the entity. Any help is much appreciated, thanks!

Link to comment
Share on other sites

2 hours ago, Luis_ST said:

the implementation of encode and decode is wrong,
in encode you need to write the Entity to the PacketBuffer
and in decode you need to read the Entity from the PacketBuffer

the entity field should als be non static and final

Thanks for the reply. How would I read and write the entity? I remember only having the methods of readint or writeint, readfloat or writefloat, etc. (only primal variables) how would I go about doing this but with an entity?

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.



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • I have a modded mob that when I try to spawn it, it won't spawn and a crash happens (doesn't crash whole game though) and it says "Duplicate id value for 16!" and points to the mob's defineSynchedData method. Anyone know what's going on?
    • Click Here -- Official Website -- Order Now ➡️● For Order Official Website - https://sale365day.com/get-restore-cbd-gummies ➡️● Item Name: — Restore CBD Gummies ➡️● Ingredients: — All Natural ➡️● Incidental Effects: — NA ➡️● Accessibility: — Online ✅HUGE DISCOUNT ! HURRY UP! ORDER NOW!✅ ✅HUGE DISCOUNT ! HURRY UP! ORDER NOW!✅ ✅HUGE DISCOUNT ! HURRY UP! ORDER NOW!✅   Restore CBD Gummies is a strong contender for the top gummy of the year. Due to its strong concentration of CBD and purity, you will achieve excellent results while using it if you stick with this solution. Most people who suffer from constant pain, anxiety, depression, and insomnia are currently solving these problems, and you can be the next one. All you need to do is give Restore CBD Gummies a chance and let this fantastic product change your life. Visit the official website to order your Restore CBD Gummies today! After reading Restore CBD Gummies reviews, we now know that knee replacement surgeries are not the only option to treat knee pain, inflammation, joint discomfort, and stiffness. These CBD gummies can heal your joints and provide you relief from pain and stress so that you can lead a happy life. Prosper Wellness Restore CBD Gummies can improve joint mobility and improve knee health so that you can remain healthy. Exclusive Details: *Restore CBD Gummies* Read More Details on Official Website #USA! https://www.facebook.com/claritox.pro.unitedstates https://www.facebook.com/illudermaUCAAU https://www.facebook.com/awakenxtusa https://groups.google.com/a/chromium.org/g/chromium-reviews/c/8NMUVKgd-FA https://groups.google.com/g/microsoft.public.project/c/0UZQQKOZF58 https://groups.google.com/g/comp.editors/c/r_BcRRrvGhs https://medium.com/@illuderma/illuderma-reviews-fda-approved-breakthrough-or-clever-skincare-scam-36088ae82c3e https://medium.com/@claritoxpros/claritox-pro-reviews-legitimate-or-deceptive-dr-warns-of-potential-dangers-d5ff3867b34d https://medium.com/@thedetoxall17/detoxall-17-reviews-scam-alert-or-legit-detox-solution-customer-report-inside-1fd4c6920c9e https://groups.google.com/a/chromium.org/g/chromium-reviews/c/RONgLAl6vwM https://groups.google.com/g/microsoft.public.project/c/TgtOMRFt6nQ https://groups.google.com/g/comp.editors/c/fUfg0L2YfzU https://crediblehealths.blogspot.com/2023/12/revitalize-with-restore-cbd-gummies.html https://community.weddingwire.in/forum/restore-cbd-gummies-uncovered-fda-approved-breakthrough-or-deceptive-wellness-scam--t206896 https://restorecbdgummies.bandcamp.com/album/restore-cbd-gummies-uncovered-fda-approved https://my-restore-cb.clubeo.com/page/restore-cbd-gummies-reviews-customer-alert-drs-warning-genuine-or-wellness-hoax.html https://my-restore-cb.clubeo.com/page/restore-cbd-gummies-reviews-scam-alert-or-legit-relief-solution-customer-report-inside.html https://medium.com/@restorecbdgum/restore-cbd-gummies-reviews-warning-2023-update-real-or-a-powerful-relief-hoax-caution-350b61472a3f https://devfolio.co/@restorecbdgum https://restore-cbd-gummies-9.jimdosite.com/ https://devfolio.co/project/new/restore-cbd-gummies-reviews-scam-or-legit-custo-7bd6 https://groups.google.com/a/chromium.org/g/chromium-reviews/c/R0enUCvfs8s https://groups.google.com/g/microsoft.public.project/c/miJma2yOMDQ https://groups.google.com/g/comp.os.vms/c/S_HG94aaKFo https://groups.google.com/g/mozilla.dev.platform/c/qb6WpMUYLu0 https://hellobiz.in/restore-cbd-gummies-reviews-warning-2023-update-genuine-wellness-or-another-hoax-caution-211948390 https://pdfhost.io/v/ir5l.cseV_Restore_CBD_Gummies_Reviews_WARNING_2023_Update_Genuine_Wellness_or_Another_Hoax_Caution https://odoe.powerappsportals.us/en-US/forums/general-discussion/7c8b3f62-6d96-ee11-a81c-001dd8066f2b https://gamma.app/public/Restore-CBD-Gummies-ssh57nprs2l6xgq https://restorecbdgummies.quora.com/ https://www.facebook.com/RestoreCBDGummiesUS https://groups.google.com/g/restorecbdgum/c/9KHVNp3oy3E https://sites.google.com/view/restorecbdgummiesreviewsfdaapp/home https://experiment.com/projects/pjyhtzvpcvllopsglcph/methods https://lookerstudio.google.com/reporting/e5e9f52d-ae52-4c84-96c6-96b97932215f/page/XtkkD https://restore-cbd-gummies-reviews-is-it-a-sca.webflow.io/ https://colab.research.google.com/drive/1xZoc6E2H-jliBSZRVl0vnVqrkc3ix4YU https://soundcloud.com/restore-cbd-gummies-821066674/restore-cbd-gummies https://www.eventcreate.com/e/restore-cbd-gummies-reviews https://restorecbdgummies.godaddysites.com/ https://sketchfab.com/3d-models/restore-cbd-gummies-reviews-fda-approved-7cfe1fb8b003481c81689dd9489d2812 https://www.scoop.it/topic/restore-cbd-gummies-by-restore-cbd-gummies-9 https://events.humanitix.com/restore-cbd-gummies https://communityforums.atmeta.com/t5/General-Development/Restore-CBD-Gummies/m-p/1113602
    • Click Here -- Official Website -- Order Now ➡️● For Order Official Website - https://sale365day.com/get-restore-cbd-gummies ➡️● Item Name: — Restore CBD Gummies ➡️● Ingredients: — All Natural ➡️● Incidental Effects: — NA ➡️● Accessibility: — Online ✅HUGE DISCOUNT ! HURRY UP! ORDER NOW!✅ ✅HUGE DISCOUNT ! HURRY UP! ORDER NOW!✅ ✅HUGE DISCOUNT ! HURRY UP! ORDER NOW!✅   Restore CBD Gummies is a strong contender for the top gummy of the year. Due to its strong concentration of CBD and purity, you will achieve excellent results while using it if you stick with this solution. Most people who suffer from constant pain, anxiety, depression, and insomnia are currently solving these problems, and you can be the next one. All you need to do is give Restore CBD Gummies a chance and let this fantastic product change your life. Visit the official website to order your Restore CBD Gummies today! After reading Restore CBD Gummies reviews, we now know that knee replacement surgeries are not the only option to treat knee pain, inflammation, joint discomfort, and stiffness. These CBD gummies can heal your joints and provide you relief from pain and stress so that you can lead a happy life. Prosper Wellness Restore CBD Gummies can improve joint mobility and improve knee health so that you can remain healthy. Exclusive Details: *Restore CBD Gummies* Read More Details on Official Website #USA! https://www.facebook.com/claritox.pro.unitedstates https://www.facebook.com/illudermaUCAAU https://www.facebook.com/awakenxtusa https://groups.google.com/a/chromium.org/g/chromium-reviews/c/8NMUVKgd-FA https://groups.google.com/g/microsoft.public.project/c/0UZQQKOZF58 https://groups.google.com/g/comp.editors/c/r_BcRRrvGhs https://medium.com/@illuderma/illuderma-reviews-fda-approved-breakthrough-or-clever-skincare-scam-36088ae82c3e https://medium.com/@claritoxpros/claritox-pro-reviews-legitimate-or-deceptive-dr-warns-of-potential-dangers-d5ff3867b34d https://medium.com/@thedetoxall17/detoxall-17-reviews-scam-alert-or-legit-detox-solution-customer-report-inside-1fd4c6920c9e https://groups.google.com/a/chromium.org/g/chromium-reviews/c/RONgLAl6vwM https://groups.google.com/g/microsoft.public.project/c/TgtOMRFt6nQ https://groups.google.com/g/comp.editors/c/fUfg0L2YfzU https://crediblehealths.blogspot.com/2023/12/revitalize-with-restore-cbd-gummies.html https://community.weddingwire.in/forum/restore-cbd-gummies-uncovered-fda-approved-breakthrough-or-deceptive-wellness-scam--t206896 https://restorecbdgummies.bandcamp.com/album/restore-cbd-gummies-uncovered-fda-approved https://my-restore-cb.clubeo.com/page/restore-cbd-gummies-reviews-customer-alert-drs-warning-genuine-or-wellness-hoax.html https://my-restore-cb.clubeo.com/page/restore-cbd-gummies-reviews-scam-alert-or-legit-relief-solution-customer-report-inside.html https://medium.com/@restorecbdgum/restore-cbd-gummies-reviews-warning-2023-update-real-or-a-powerful-relief-hoax-caution-350b61472a3f https://devfolio.co/@restorecbdgum https://restore-cbd-gummies-9.jimdosite.com/ https://devfolio.co/project/new/restore-cbd-gummies-reviews-scam-or-legit-custo-7bd6 https://groups.google.com/a/chromium.org/g/chromium-reviews/c/R0enUCvfs8s https://groups.google.com/g/microsoft.public.project/c/miJma2yOMDQ https://groups.google.com/g/comp.os.vms/c/S_HG94aaKFo https://groups.google.com/g/mozilla.dev.platform/c/qb6WpMUYLu0 https://hellobiz.in/restore-cbd-gummies-reviews-warning-2023-update-genuine-wellness-or-another-hoax-caution-211948390 https://pdfhost.io/v/ir5l.cseV_Restore_CBD_Gummies_Reviews_WARNING_2023_Update_Genuine_Wellness_or_Another_Hoax_Caution https://odoe.powerappsportals.us/en-US/forums/general-discussion/7c8b3f62-6d96-ee11-a81c-001dd8066f2b https://gamma.app/public/Restore-CBD-Gummies-ssh57nprs2l6xgq https://restorecbdgummies.quora.com/ https://www.facebook.com/RestoreCBDGummiesUS https://groups.google.com/g/restorecbdgum/c/9KHVNp3oy3E https://sites.google.com/view/restorecbdgummiesreviewsfdaapp/home https://experiment.com/projects/pjyhtzvpcvllopsglcph/methods https://lookerstudio.google.com/reporting/e5e9f52d-ae52-4c84-96c6-96b97932215f/page/XtkkD https://restore-cbd-gummies-reviews-is-it-a-sca.webflow.io/ https://colab.research.google.com/drive/1xZoc6E2H-jliBSZRVl0vnVqrkc3ix4YU https://soundcloud.com/restore-cbd-gummies-821066674/restore-cbd-gummies https://www.eventcreate.com/e/restore-cbd-gummies-reviews https://restorecbdgummies.godaddysites.com/ https://sketchfab.com/3d-models/restore-cbd-gummies-reviews-fda-approved-7cfe1fb8b003481c81689dd9489d2812 https://www.scoop.it/topic/restore-cbd-gummies-by-restore-cbd-gummies-9 https://events.humanitix.com/restore-cbd-gummies https://communityforums.atmeta.com/t5/General-Development/Restore-CBD-Gummies/m-p/1113602
    • i use fabric 1.20.1 i used alot of mods like all the trims, bobby, better stats, and more but i encounter a problem when i try to enter my world it force me to be in safe mode and when i click on safe mode it just crash minecraft
    • Dr Oz Bites CBD Gummies: As the manufacturer isn't certain about the end result of the supplement, they are going at the back of faux paid promotions to growth the call for for the product. I felt that it's miles because of this motive, Dr Oz Bites CBD Gummies is earning a variety of popularity among the populace.   ➥ ✅Official Website: https://gummiestoday.com/Dr-Oz-Bites-CBD-Gummies/ ➥ Product Name: Dr Oz Bites CBD Gummies ➥ Benefits: Dr Oz Bites CBD Gummies Helps you to get Pain Relief ➥ Healthy Benefits :Control your hormone levels ➥ Category:Pain Relief Supplement ➥ Rating: ★★★★☆ (4.5/5.0) ➥ Side Effects: No Major Side Effects ➥ Availability: In Stock Voted #1 Product in the United States   📞📞 ✔Hurry Up🤑CLICK HERE TO BUY – “OFFICIAL WEBSITE”🎊👇〽💝💞❣️ 📞📞 ✔Hurry Up🤑CLICK HERE TO BUY – “OFFICIAL WEBSITE”🎊👇〽💝💞❣️ 📞📞 ✔Hurry Up🤑CLICK HERE TO BUY – “OFFICIAL WEBSITE”🎊👇〽💝💞❣️     FOR MORE INFO VISIT OUR OTHER LINKS :- https://www.onlymyhealth.com/dr-oz-cbd-gummies-reviews-care-cbd-shark-tank-gummies-exposed-benefits-1701579520 https://www.deccanherald.com/brandspot/featured/cbd-dr-oz-gummies-reviews-care-cbd-gummies-2023-dr-oz-gummies-is-it-worth-buying-2-2797780 https://www.onlymyhealth.com/cbd-dr-oz-gummies-diabetes-reviews-dr-oz-shark-tank-cbd-gummies-1702083884   Official Facebook Page:- https://www.facebook.com/GreenVibeCBDGummiesForDiabetes https://www.facebook.com/DrOzBitesCBDGummiesSupplement   FOR MORE INFO VISIT OUR OFFICIAL SITE :- https://groups.google.com/g/drone-dev-platform/c/X-xNP-OefLg https://groups.google.com/g/mozilla.dev.platform/c/i9X2WfOmkUs https://groups.google.com/g/mozilla.dev.platform/c/DP8vaQGqayk https://groups.google.com/g/comp.os.vms/c/V9XrF_T5u08 https://groups.google.com/g/comp.mobile.android/c/XuYes3irk9w https://groups.google.com/a/chromium.org/g/chromium-reviews/c/xCJCm9yhigE https://groups.google.com/g/comp.protocols.time.ntp/c/yErPa0A9uw0 https://groups.google.com/g/mozilla.dev.platform/c/dzcLb8COWts   Other Reference Pages JIMDO@ https://dr-oz-b-i-t-e-s-cbd-gummies.jimdosite.com/ GROUP GOOGLE@ https://groups.google.com/g/dr-oz-bites-cbd-gummies-lifestyle/c/MTpEvLDAPb0 GOOGLE SITE@ https://sites.google.com/view/drozbitescbdgummiesingredients/ GAMMA APP@ https://gamma.app/docs/Dr-Oz-Bites-CBD-GummiesIS-FAKE-or-REAL-Read-About-100-Natural-Pro-z7obrrpiq9agw3v Company sites@ https://dr-oz-bites-cbd-gummies-side-effects.company.site/   Recent Searches:- #DrOzBitesCBDGummiesReviews #DrOzBitesCBDGummiesLifestyle #DrOzBitesCBDGummiesBenefits #DrOzBitesCBDGummiesBuy #DrOzBitesCBDGummiesCost #DrOzBitesCBDGummiesIngredients #DrOzBitesCBDGummiesOrder #DrOzBitesCBDGummiesPrice #DrOzBitesCBDGummiesWebsite #DrOzBitesCBDGummiesResults #DrOzBitesCBDGummiesSideEffects #DrOzBitesCBDGummiesAdvantage #DrOzBitesCBDGummiesOffers #DrOzBitesCBDGummiesSupplement #DrOzBitesCBDGummiesBuyNow #DrOzBitesCBDGummiesFormula #DrOzBitesCBDGummiesHowToUse Our Official Blog Link Below:- BLOGSPOT==>>https://dr-oz-bites-cbd-gummies-advantage.blogspot.com/2023/12/Dr-Oz-Bites-CBD-Gummies.html Sunflower==>>https://www.sunflower-cissp.com/glossary/cissp/7068/dr-oz-bites-cbd-gummies-reviews-dr-oz-bites-cbd-gummies-where-to-buy Lawfully ==>>https://www.lawfully.com/community/posts/dr-oz-bites-cbd-gummies-navigating-the-wellness-landscape-BYTaVtWKNIUrHsIxGaivMA%3D%3D DIBIZ==>>https://www.dibiz.com/morrislymorales   Medium==>>https://medium.com/@elizabekennedy/is-dr-oz-bites-cbd-gummies-brand-legit-34cfcab397be   Devfolio==>>https://devfolio.co/projects/how-many-dr-oz-bites-cbd-gummies-need-to-i-take-cdf6        
  • Topics

×
×
  • Create New...

Important Information

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