如何获取玩家正在查看的方块的坐标? [英] How can I get the coordinates of a block the player is looking at?

查看:51
本文介绍了如何获取玩家正在查看的方块的坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取玩家正在查看的方块的坐标.我尝试这样做:

I want to get the coordinates of the block the player is looking at. I tried to do it with:

double x = player.getLookVec().getX();
double y = player.getLookVec().getY();
double z = player.getLookVec().getZ();

但不知何故,这些数字总是在 0、0、0 和 1、1、1 之间,所以我没有得到块的坐标.那么我怎样才能得到一个块的确切坐标呢?

But somehow these numbers are always between 0, 0, 0, and 1, 1, 1, so I didn't get the coordinates of the block. So how can I get the exact coordinates of a block?

更多代码:

@Mod.EventBusSubscriber (modid = FirstMod.MOD_ID, bus = Bus.FORGE)
public class RightClickBlock 
{           

    @SubscribeEvent 
    public static void on(FOVUpdateEvent event) 

    {
          if(player.getHeldItemMainhand().getItem() == Items.BEDROCK) 
        {   
             LivingEntity player = event.getEntity();
                 World worldIn = player.world;

                double x = player.getLookVec().getX();
                double y = player.getLookVec().getY();
                double z = player.getLookVec().getZ(); `

                worldIn.setBlockState(new BlockPos(x, y, z) , Blocks.BEDROCK.getDefaultState());   
         }
    }
}

推荐答案

我注意到(至少在 1.16 中)Minecraft.getInstance().objectMouseOver.getHitVec() 如果玩家看起来像空气一样返回在从南、东或上侧的街区.如果数字太大,它会给出旁边的块.此方法使用球员位置,如果双以.0结束,则决定什么时候位置需要-1.

I noticed (at least in 1.16) Minecraft.getInstance().objectMouseOver.getHitVec() returns as air if the player looks at the block from the south, east, or up side. It gives the block next to it, if the number is too big. This method uses the players position, and if the double ends in .0, and decides when the position needs to be -1.

Minecraft instance = Minecraft.getInstance();

if(instance.objectMouseOver.getType() != RayTraceResult.Type.BLOCK){return;}

Vector3d blockVector = instance.objectMouseOver.getHitVec();

double bX = blockVector.getX(); double bY = blockVector.getY(); double bZ = blockVector.getZ();
double pX = instance.player.getPosX(); double pY = instance.player.getPosY(); double pZ = instance.player.getPosZ();

if(bX == Math.floor(bX) && bX <= pX){bX--;}
if(bY == Math.floor(bY) && bY <= pY+1){bY--;} // +1 on Y to get y from player eyes instead of feet
if(bZ == Math.floor(bZ) && bZ <= pZ){bZ--;}

BlockState block = instance.world.getBlockState(new BlockPos(bX, bY, bZ));

这篇关于如何获取玩家正在查看的方块的坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆