【问题标题】:3D picking in LWJGLLWJGL 中的 3D 拾取
【发布时间】:2026-02-09 08:20:03
【问题描述】:

我正在制作一个 Minecraft 风格的游戏,将块的 3D 阵列分成块。但是然后我需要检查块播放器指向什么来执行世界修改。到目前为止,这是我想出的:

    private Block getBlockLookedAt(EntityPlayer ep) {


        double px = ep.getPosition().x;
        double py = ep.getPosition().y;
        double pz = ep.getPosition().z;

        float pPitch = ep.getPitch()*-1;
        float pYaw = ep.getYaw()*-1;

        double searchRadius = 6;

        double targetX = searchRadius * Math.cos(Math.toRadians(pYaw))*Math.sin(Math.toRadians(pPitch));
        double targetY = searchRadius * Math.sin(Math.toRadians(pYaw))*Math.sin(Math.toRadians(pPitch));
        double targetZ = searchRadius * Math.cos(Math.toRadians(pPitch));
        //System.out.println("=");
        //System.out.println(px + "," + py + "," + pz);
        //System.out.println(targetX + "," + targetY + "," + targetZ);
        //System.out.println("=");
        for(double i = 0; i<searchRadius; i+=0.01){
            targetX = i * Math.cos(Math.toRadians(pYaw))*Math.sin(Math.toRadians(pPitch));
            targetY = i * Math.sin(Math.toRadians(pYaw))*Math.sin(Math.toRadians(pPitch));
            targetZ = i * Math.cos(Math.toRadians(pPitch));
            int bx = (int)Math.ceil(targetX+px);
            int by = (int)Math.ceil((targetY*-1)+py);
            int bz = (int)Math.ceil(targetZ+pz);
            System.out.println(bx + "," + by + "," + bz + "," + getBlock(bx,by,bz).getID());
            if(getBlock(bx,by,bz).getID()!=0)return getBlock(bx,by,bz);
        }



        return Block.air;
    }

我在这里所做的是使用球坐标,并在检查半径中添加 0.01 以检查范围内是否存在与空气不同的块。虽然这似乎不起作用(它总是返回空气,我需要在块内才能检测到其他块) 有人有解决方案,或者有更好的方法吗?

附言。我已经阅读了 schabby 的教程,据我理解,它不会检查 Z 轴,所以这不是我想要的。

【问题讨论】:

    标签: java opengl lwjgl


    【解决方案1】:
    double searchRadius = 0;
    ...
    for(double i = 0; i<searchRadius; i+=0.01){
        ...
    }
    return Block.air;
    

    试试大于零的searchRadius

    【讨论】:

    • 我将 searchRadius 设为 6,尽管它仍然只输出 0。