Jump to content

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


Recommended Posts

Posted (edited)

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
Posted

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.

Posted
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?

Posted (edited)
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
  • Warven22 changed the title to (SOLVED) [1.17.1] Getting Entity That Player Is Pointing At
Posted

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);
}
Guest
This topic is now closed to further replies.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Im trying to build my mod using shade since i use the luaj library however i keep getting this error Reason: Task ':reobfJar' uses this output of task ':shadowJar' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. So i try adding reobfJar.dependsOn shadowJar  Could not get unknown property 'reobfJar' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler. my gradle file plugins { id 'eclipse' id 'idea' id 'maven-publish' id 'net.minecraftforge.gradle' version '[6.0,6.2)' id 'com.github.johnrengelman.shadow' version '7.1.2' id 'org.spongepowered.mixin' version '0.7.+' } apply plugin: 'net.minecraftforge.gradle' apply plugin: 'org.spongepowered.mixin' apply plugin: 'com.github.johnrengelman.shadow' version = mod_version group = mod_group_id base { archivesName = mod_id } // Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17. java.toolchain.languageVersion = JavaLanguageVersion.of(17) //jarJar.enable() println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" minecraft { mappings channel: mapping_channel, version: mapping_version copyIdeResources = true runs { configureEach { workingDirectory project.file('run') property 'forge.logging.markers', 'REGISTRIES' property 'forge.logging.console.level', 'debug' arg "-mixin.config=derp.mixin.json" mods { "${mod_id}" { source sourceSets.main } } } client { // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. property 'forge.enabledGameTestNamespaces', mod_id } server { property 'forge.enabledGameTestNamespaces', mod_id args '--nogui' } gameTestServer { property 'forge.enabledGameTestNamespaces', mod_id } data { workingDirectory project.file('run-data') args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') } } } sourceSets.main.resources { srcDir 'src/generated/resources' } repositories { flatDir { dirs './libs' } maven { url = "https://jitpack.io" } } configurations { shade implementation.extendsFrom shade } dependencies { minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" implementation 'org.luaj:luaj-jse-3.0.2' implementation fg.deobf("com.github.Virtuoel:Pehkui:${pehkui_version}") annotationProcessor 'org.spongepowered:mixin:0.8.5:processor' minecraftLibrary 'luaj:luaj-jse:3.0.2' shade 'luaj:luaj-jse:3.0.2' } // Example for how to get properties into the manifest for reading at runtime. tasks.named('jar', Jar).configure { manifest { attributes([ 'Specification-Title' : mod_id, 'Specification-Vendor' : mod_authors, 'Specification-Version' : '1', // We are version 1 of ourselves 'Implementation-Title' : project.name, 'Implementation-Version' : project.jar.archiveVersion, 'Implementation-Vendor' : mod_authors, 'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"), "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", "TweakOrder" : 0, "MixinConfigs" : "derp.mixin.json" ]) } rename 'mixin.refmap.json', 'derp.mixin-refmap.json' } shadowJar { archiveClassifier = '' configurations = [project.configurations.shade] finalizedBy 'reobfShadowJar' } assemble.dependsOn shadowJar reobf { re shadowJar {} } publishing { publications { mavenJava(MavenPublication) { artifact jar } } repositories { maven { url "file://${project.projectDir}/mcmodsrepo" } } }  
    • Todas as versões do Minecraft Forge são repentinamente tela preta, mesmo sem mods (tentei reinstalar o Minecraft original, Java, atualizar os drivers não funciona)
    • When i join minecraft all ok, when i join world all working fine, but when i open indentity menu, i get this The game crashed whilst unexpected error Error: java.lang.NullPointerException: Cannot invoke "top.ribs.scguns.common.Gun$Projectile.getDamage()" because "this.projectile" is null crash report here https://paste.ee/p/0vKaf
  • Topics

×
×
  • Create New...

Important Information

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