Jump to content

(SOLVED) [1.17.1] Getting Entity That Player Is Pointing At


Warven22

Recommended Posts

I need to know how to get the mob a player is pointing at from some distance (not just regular reach distance). I looked around quite a lot in both Google and source code, but I find myself stumped, confused, and unsure.

I attempted this:

public static EntityHitResult getTargetedEntity(Player player) {
  Vec3 start = player.getEyePosition();
  Vec3 addition = player.getLookAngle().multiply(new Vec3(10000D, 10000D, 10000D));
  return ProjectileUtil.getEntityHitResult(
  	player.level, 
  	player,
  	start,
  	start.add(addition),
  	player.getBoundingBox().expandTowards(player.getDeltaMovement()).inflate(1.0D),
	(val) -> true);
}

It seems to work, but the range is very short regardless of the number I multiply with.

Am I misunderstanding this function? Is there a better way to get the entity the player is pointing at?

Edited by Warven22
Solved
Link to comment
Share on other sites

3 hours ago, poopoodice said:

The problem is it's only gathering the entities that are inside/intersects with the bb:

player.getBoundingBox().expandTowards(player.getDeltaMovement()).inflate(1.0D)

So make the bounding box bigger.

I've tried expandingTowards using

player.getLookAngle().multiply(new Vec3(10000D, 10000D, 10000D));

rather than the player's movement (since movement can be 0), along with an inflate of a similarly large number. My range seems to have increased, but not as expected, as if I'm not visualizing how these changes to the bounding box actually affects anything. Can I set up this bounding box to be drawn in the debug elsewhere?

I feel like I do not understand how the ProjectileUtil works. I don't like the idea that I'm "shooting" the player towards a point, but it seems to be the only way.

Is there no other way for this to be done? No raycast function? No better way all the other modders use?

Link to comment
Share on other sites

8 hours ago, Luis_ST said:

did you read poopoodice post? since expanding the LookAngle != BoundingBox

I should have made it more clear that I did try that solution and what I actually did:

Vec3 start = player.getEyePosition();
Vec3 addition = player.getLookAngle().multiply(new Vec3(1000000D, 1000000D, 1000000D));
return ProjectileUtil.getEntityHitResult(
  player.level, player,
  start, start.add(addition),
  player.getBoundingBox().expandTowards(addition).inflate(1000000D), (val) -> true);

It didn't seem to work, as the range doesn't seem as big as it should be, needing me to be a few blocks (around 10) away rather than anything in view.

Edited by Warven22
clarification, less snarky wording
Link to comment
Share on other sites

  • Warven22 changed the title to (SOLVED) [1.17.1] Getting Entity That Player Is Pointing At

Please forgive this additional bump, but I want to assist future google visitors by sharing my solution.

I have found a solution by using a combination of two different functions: ProjectileUtil.getEntityHitResult & Item.getPlayerPOVHitResult.

getEntityHitResult
doesn't take into account player's rotation. getPlayerPOVHitResult is for blocks, but takes into account player's rotation. So by using the positions from getPlayerPOVHitResult, creating a bounding box from it, and using the loop for entities in getEntityHitResult, it creates a raycast function that fires from the player's eyes to where they are pointing.

I'm not sure if any of that is right, but one thing I'm sure of is it works. If you increase the range to a high number, you can detect an entity quite far away.

public static EntityHitResult getPlayerPOVHitResult(Player player) {
  float playerRotX = player.getXRot();
  float playerRotY = player.getYRot();
  Vec3 startPos = player.getEyePosition();
  float f2 = Mth.cos(-playerRotY * ((float)Math.PI / 180F) - (float)Math.PI);
  float f3 = Mth.sin(-playerRotY * ((float)Math.PI / 180F) - (float)Math.PI);
  float f4 = -Mth.cos(-playerRotX * ((float)Math.PI / 180F));
  float additionY = Mth.sin(-playerRotX * ((float)Math.PI / 180F));
  float additionX = f3 * f4;
  float additionZ = f2 * f4;
  double d0 = ZapEffect.RANGE;
  Vec3 endVec = startPos.add((double)additionX * d0, (double)additionY * d0, (double)additionZ * d0);
  AABB startEndBox = new AABB(startPos, endVec);
  Entity entity = null;
  for(Entity entity1 : player.level.getEntities(player, startEndBox, (val) -> true)) {
	AABB aabb = entity1.getBoundingBox().inflate(entity1.getPickRadius());
	Optional<Vec3> 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()) {
      Vec3 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 EntityHitResult(entity);
}
Link to comment
Share on other sites

Guest
This topic is now closed to further replies.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Compare this list (client-side-only mods) with your mods: https://www.dropbox.com/scl/fi/yeldxfv8ed60e4uflc2fi/Client-Side-Only-Modlist.xlsx?rlkey=8376c5bk7b33je2tad4p3ybrg&st=qf6osvit&dl=0  
    • Crashlog: https://paste.ee/p/WrGYD I'm thinking the problem might be a client side mod but ive already checked the mod list like 5 times and still cant find the problem
    • I'm unable to join my local forge servers. When running my forge servers of seemingly any version (tested 1.18 to 1.21.1) I get an error message [Forge Version Check/WARN] [ne.mi.fm.VersionChecker/]: Failed to process update information The server continues to start up and run, however I'm unable to join. Looking for solutions? Full error message: (note last "thead warning" error seems to be unrelated and only happened once for 1.20.1) Forge version check warning has happened for every version. [09:52:31] [Forge Version Check/WARN] [ne.mi.fm.VersionChecker/]: Failed to process update information java.net.http.HttpConnectTimeoutException: HTTP connect timed out         at jdk.internal.net.http.HttpClientImpl.send(HttpClientImpl.java:950) ~[java.net.http:?] {}         at jdk.internal.net.http.HttpClientFacade.send(HttpClientFacade.java:133) ~[java.net.http:?] {}         at net.minecraftforge.fml.VersionChecker$1.openUrlString(VersionChecker.java:142) ~[fmlcore-1.20.1-47.3.10.jar%23102!/:?] {}         at net.minecraftforge.fml.VersionChecker$1.process(VersionChecker.java:180) ~[fmlcore-1.20.1-47.3.10.jar%23102!/:?] {}         at java.lang.Iterable.forEach(Iterable.java:75) ~[?:?] {}         at net.minecraftforge.fml.VersionChecker$1.run(VersionChecker.java:117) ~[fmlcore-1.20.1-47.3.10.jar%23102!/:?] {} Caused by: java.net.http.HttpConnectTimeoutException: HTTP connect timed out         at jdk.internal.net.http.ResponseTimerEvent.handle(ResponseTimerEvent.java:68) ~[java.net.http:?] {}         at jdk.internal.net.http.HttpClientImpl.purgeTimeoutsAndReturnNextDeadline(HttpClientImpl.java:1788) ~[java.net.http:?] {}         at jdk.internal.net.http.HttpClientImpl$SelectorManager.run(HttpClientImpl.java:1385) ~[java.net.http:?] {} Caused by: java.net.ConnectException: HTTP connect timed out         at jdk.internal.net.http.ResponseTimerEvent.handle(ResponseTimerEvent.java:69) ~[java.net.http:?] {}         at jdk.internal.net.http.HttpClientImpl.purgeTimeoutsAndReturnNextDeadline(HttpClientImpl.java:1788) ~[java.net.http:?] {}         at jdk.internal.net.http.HttpClientImpl$SelectorManager.run(HttpClientImpl.java:1385) ~[java.net.http:?] {} [09:52:31] [Yggdrasil Key Fetcher/ERROR] [mojang/YggdrasilServicesKeyInfo]: Failed to request yggdrasil public key com.mojang.authlib.exceptions.AuthenticationUnavailableException: Cannot contact authentication server         at com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService.makeRequest(YggdrasilAuthenticationService.java:119) ~[authlib-4.0.43.jar%2375!/:?] {}         at com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService.makeRequest(YggdrasilAuthenticationService.java:91) ~[authlib-4.0.43.jar%2375!/:?] {}         at com.mojang.authlib.yggdrasil.YggdrasilServicesKeyInfo.fetch(YggdrasilServicesKeyInfo.java:94) ~[authlib-4.0.43.jar%2375!/:?] {}         at com.mojang.authlib.yggdrasil.YggdrasilServicesKeyInfo.lambda$get$1(YggdrasilServicesKeyInfo.java:81) ~[authlib-4.0.43.jar%2375!/:?] {}         at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:572) ~[?:?] {}         at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:358) ~[?:?] {}         at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305) ~[?:?] {}         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144) ~[?:?] {}         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642) ~[?:?] {}         at java.lang.Thread.run(Thread.java:1575) ~[?:?] {} Caused by: java.net.SocketTimeoutException: Connect timed out         at sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:546) ~[?:?] {}         at sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:592) ~[?:?] {}         at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327) ~[?:?] {}         at java.net.Socket.connect(Socket.java:760) ~[?:?] {}         at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:304) ~[?:?] {}         at sun.net.NetworkClient.doConnect(NetworkClient.java:178) ~[?:?] {}         at sun.net.www.http.HttpClient.openServer(HttpClient.java:531) ~[?:?] {}         at sun.net.www.http.HttpClient.openServer(HttpClient.java:636) ~[?:?] {}         at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264) ~[?:?] {}         at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:377) ~[?:?] {}         at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:193) ~[?:?] {}         at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1273) ~[?:?] {}         at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1114) ~[?:?] {}         at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:179) ~[?:?] {}         at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1676) ~[?:?] {}         at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1600) ~[?:?] {}         at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:223) ~[?:?] {}         at com.mojang.authlib.HttpAuthenticationService.performGetRequest(HttpAuthenticationService.java:140) ~[authlib-4.0.43.jar%2375!/:?] {}         at com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService.makeRequest(YggdrasilAuthenticationService.java:96) ~[authlib-4.0.43.jar%2375!/:?] {}         ... 9 more [09:52:31] [Server thread/WARN] [minecraft/MinecraftServer]: Can't keep up! Is the server overloaded? Running 5985ms or 119 ticks behind
    • Remove the mod tempad from the mods-folder
    • Hi, deleting the config folder did not appear to work, what mod are you referring to I could try to delete to fix the problem?
  • Topics

×
×
  • Create New...

Important Information

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