代码之家  ›  专栏  ›  技术社区  ›  Christopher Koho

为什么Location.add(0,1,0)不在一个街区上方设置一个新位置?

  •  2
  • Christopher Koho  · 技术社区  · 10 年前

    我想,如果玩家打破了一个区块,也打破了上面的区块,但这段代码只会删除原始区块( brokenBlock )甚至没有打破上面的障碍。。。

    我做错了什么?

    @EventHandler
    public void onDestroy(BlockBreakEvent event)
    {
        Player player = event.getPlayer();
    
        if (player.getItemInHand().getType() == Material.WOOD_PICKAXE)
        {
            Location brokenBlock = event.getBlock().getLocation();
    
            Location up = brokenBlock.add(0, 1, 0);
            up.getBlock().breakNaturally();
        }
    }
    

    经过一些实验,我发现了问题,但没有找到答案。

    我把上面的代码做得更短,所以读起来更好,但原始代码包含两个breakNaturally()方法。当我尝试同时执行这两个或多个方法时,它的行为很奇怪,不再有效。

    这是真实的代码:

    @EventHandler
    public void onDestroy(BlockBreakEvent event)
    {
        Player player = event.getPlayer();
    
        if (player.getItemInHand().getType() == Material.WOOD_PICKAXE)
        {
            Location brokenBlock = event.getBlock().getLocation();
    
            Location up = brokenBlock.add(0, 1, 0);
            Location down = brokenBlock.add(0, -1, 0);
    
            up.getBlock().breakNaturally();
            down.getBlock().breakNaturally();
        }
    }
    
    1 回复  |  直到 10 年前
        1
  •  0
  •   Unihedron    10 年前

    注意:由于DMCA请求删除了Bukkit,因此CraftBukkit代码的相关资源链接现在不可用,它们将链接到Bukkit出血并受到链接损坏。

    与你的信念相反, Location 对象是 @Immutable (如对象的不变性,而不是注释)。首先,这里有 Location.add(double, double, double) :

    /**
     * Adds the location by another. Not world-aware.
     *
     * @see Vector
     * @param x X coordinate
     * @param y Y coordinate
     * @param z Z coordinate
     * @return the same location
     */
    public Location add(double x, double y, double z) {
        this.x += x;
        this.y += y;
        this.z += z;
        return this;
    }
    

    如您所见,字段在过程中会发生更改并返回自身。这是因为位置操作重用自身以提高效率,而不是必须调用 new 构造和缓存对象。

    每次更换时最好使用它们:

    /* (BlockBreakEvent event) */ {
        Location brokenBlock = event.getBlock().getLocation();
    
        for (int i = 1; i < 16; i++)
            brokenBlock.add(0, i, 0).getBlock().breakNaturally();
    }