这是我的简单脚本:
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循环中一直在变化,我希望防止这种情况。
答案 0 :(得分: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);
}
}
}
}
答案 1 :(得分: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);
}
}
答案 2 :(得分:0)
我知道这个问题已经得到解答,但我希望提出一种更有效的方法。在Location中添加和减去效率非常低,尤其是在嵌套循环中执行此操作时。
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);
}
}
}
}
如果性能是个问题,我甚至会考虑在for循环之外的局部变量中缓存getWorld()。