0

这是我的简单脚本:

public void cast(Player caster) {
    Location loc = caster.getTargetBlock(null, 512).getLocation();

    for (int c = 0; c < 2; c++) {
        for (int b = 0; b < 2; b++) {
            for (int a = 0; a < 1; a++) {
                caster.sendMessage("" + loc);
                Block ice = caster.getWorld().getBlockAt(loc.add(a, b, c));
                ice.setTypeId(79);
            }
        }
    }
}

我试图让它loc保持静止不变。它在整个 for 循环中一直在变化,我希望防止这种情况发生。

4

3 回答 3

0

Loc 很可能有一个内部状态,它每次都在递增而不是重置

public void cast(Player caster){
Location loc = caster.getTargetBlock(null, 512).getLocation();

int initalC = 0;
int initalB = 0;
int initalA = 0;
Location staticLoc;
for (int c = initalC; c < 2; c++)
{
    for (int b = initalB; b < 2; b++)
    {
        for (int a = initalA; a < 1; a++)
        {
            if (a == initalA && b == initalB && c == initalC) {
                 staticLoc = caster.getTargetBlock(null, 512).getLocation().add(a, b, c);
            }

            loc = staticLoc;
            caster.sendMessage("" + loc);
            Block ice = caster.getWorld().getBlockAt(staticLoc.add(a, b, c));
            ice.setTypeId(79);
        }
    }
}

}

于 2012-12-11T05:49:42.150 回答
0

找到答案:

public void cast(Player caster){
    Location loc = caster.getTargetBlock(null, 512).getLocation();
    for (int c = -3; c < 3; c++)
        for (int b = -1; b < 5; b++)
            for (int a = -3; a < 3; a++) {
                Block ice = caster.getWorld().getBlockAt(loc.add(a, b, c));
                ice.setTypeId(79);
                loc = loc.subtract(a, b, c);
            }
}
于 2012-12-11T06:19:17.553 回答
0

我知道这个问题已经得到解答,但我希望提出一种更有效的方法。从位置中添加和减去是非常低效的,尤其是在嵌套循环中执行此操作时。

Location 对象有一个clone()方法,它返回一个相同的 Location 但不是对原始位置的引用。所以真的,你需要做的就是:

public void cast(Player caster) {
    Location loc = caster.getTargetBlock(null, 512).getLocation();

    for (int c = 0; c < 2; c++) {
        for (int b = 0; b < 2; b++) {
            for (int a = 0; a < 1; a++) {
                caster.sendMessage("" + loc);
                caster.getWorld().getBlockAt(loc.clone().add(a, b, c)).setTypeId(79);
           }
        }
    }
}

如果性能是一个问题,我什至会考虑将 getWorld() 缓存在 for 循环之外的局部变量中。

于 2013-01-03T19:14:56.067 回答