我有一名球员,当然能够以矢量形式抓住球员面对的方向。
使用此向量,我需要计算玩家是否正在查看x
个区块内的实体以及是否有“咒语”命中它。如果实体前面有任何东西,我还需要考虑。
到目前为止,我的思维过程已经到了第一位,获得了播放器x
块中所有实体的列表。但从那里,我不知道。
任何帮助我走向正确方向的帮助都会很棒。
答案 0 :(得分:3)
我编辑的代码更精确,更简单,不会通过块。但你的方法很好:D
public static Entity getNearestEntityInSight(Player player, int range) {
ArrayList<Entity> entities = (ArrayList<Entity>) player.getNearbyEntities(range, range, range);
ArrayList<Block> sightBlock = (ArrayList<Block>) player.getLineOfSight( (Set<Material>) null, range);
ArrayList<Location> sight = new ArrayList<Location>();
for (int i = 0;i<sightBlock.size();i++)
sight.add(sightBlock.get(i).getLocation());
for (int i = 0;i<sight.size();i++) {
for (int k = 0;k<entities.size();k++) {
if (Math.abs(entities.get(k).getLocation().getX()-sight.get(i).getX())<1.3) {
if (Math.abs(entities.get(k).getLocation().getY()-sight.get(i).getY())<1.5) {
if (Math.abs(entities.get(k).getLocation().getZ()-sight.get(i).getZ())<1.3) {
return entities.get(k);
}
}
}
}
}
return null; //Return null/nothing if no entity was found
}
答案 1 :(得分:2)
在我看来,让所有实体都在玩家的某个范围内的思维过程是一个良好的开端!下面是一个方法示例,该方法使用玩家视线(光线跟踪)中的块来查找最近的未被遮挡的实体。
public static Entity getNearestEntityInSight(Player player, int range) {
List<Entity> entities = player.getNearbyEntities(range, range, range); //Get the entities within range
Iterator<Entity> iterator = entities.iterator(); //Create an iterator
while (iterator.hasNext()) {
Entity next = iterator.next(); //Get the next entity in the iterator
if (!(next instanceof LivingEntity) || next == player) { //If the entity is not a living entity or the player itself, remove it from the list
iterator.remove();
}
}
List<Block> sight = player.getLineOfSight((Set) null, range); //Get the blocks in the player's line of sight (the Set is null to not ignore any blocks)
for (Block block : sight) { //For each block in the list
if (block.getType() != Material.AIR) { //If the block is not air -> obstruction reached, exit loop/seach
break;
}
Location low = block.getLocation(); //Lower corner of the block
Location high = low.clone().add(1, 1, 1); //Higher corner of the block
AxisAlignedBB blockBoundingBox = AxisAlignedBB.a(low.getX(), low.getY(), low.getZ(), high.getX(), high.getY(), high.getZ()); //The bounding or collision box of the block
for (Entity entity : entities) { //For every living entity in the player's range
//If the entity is truly close enough and the bounding box of the block (1x1x1 box) intersects with the entity's bounding box, return it
if (entity.getLocation().distance(player.getEyeLocation()) <= range && ((CraftEntity) entity).getHandle().getBoundingBox().b(blockBoundingBox)) {
return entity;
}
}
}
return null; //Return null/nothing if no entity was found
}
注意:使用上述方法时,需要考虑一些事项/潜在的错误: