问题描述
我正在制作一个迷你游戏插件,我想让玩家通过右键单击两个相对的角为游戏定义一个区域。我的想法是让代码告诉您单击一个块,一旦选择一个块,它将告诉您选择另一个块。此后,它将继续并打开GUI以完成迷你游戏的创建。我的第一次尝试是这样做的,因此在选择第一个块之后,它会切换一个变量,说已选择了第一个角,然后有另一个if语句等待您选择下一个角。但是当切换变量时,它将立即运行下一个if语句并同时设置两个块。
@EventHandler
public void onRightClick(PlayerInteractEvent event) {
Player player = event.getPlayer();
Integer pos = 0;
if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
if (event.getHand() == EquipmentSlot.OFF_HAND) {
return;
}
if (player.getItemInHand().equals(MapSelectorTool.MapSelector)) {
Block block = event.getClickedBlock();
String world = block.getWorld().getName();
Integer X = block.getX();
Integer Y = block.getY();
Integer Z = block.getZ();
if (pos.equals(0)) {
String[] pos1 = {
X.toString(),Y.toString(),Z.toString(),world
};
player.sendMessage(ChatColor.GOLD + "First position at " + ChatColor.WHITE + ChatColor.BOLD + X + " " + Y + " " + Z + " " + ChatColor.GOLD + "Now right click second position");
pos = 1;
}
}
}
}
解决方法
问题是您在onRightClick
方法中使用了局部变量,例如,Integer pos = 0;
将始终在每次右键单击时重置。您需要将变量存储在方法之外,以使该变量在第二次单击时保持不变,否则您将永远无法进行两次单独的单击并将其链接。
//Place the key variables outside of the method/event (They may need to be static depending on how you wrote the code)
Player player;
Integer pos = 0;
String[] pos1;
String[] pos2;
public void onRightClick(PlayerInteractEvent event) {
player = event.getPlayer();
if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
if (event.getHand() == EquipmentSlot.OFF_HAND) {
return;
}
if (player.getItemInHand().equals(MapSelectorTool.MapSelector)) {
Block block = event.getClickedBlock();
String world = block.getWorld().getName();
Integer X = block.getX();
Integer Y = block.getY();
Integer Z = block.getZ();
if (pos.equals(0)) {
pos1 = {X.toString(),Y.toString(),Z.toString(),world};
player.sendMessage(ChatColor.GOLD + "First position at " + ChatColor.WHITE + ChatColor.BOLD + X + " " + Y + " " + Z + " " + ChatColor.GOLD + "now right click second position");
pos = 1;
}
else if (pos.equals(1)) {
pos2 = {X.toString(),world};
player.sendMessage(ChatColor.GOLD + "Second position at " + ChatColor.WHITE + ChatColor.BOLD + X + " " + Y + " " + Z);
pos = 0;
//Now do your other code to process the positions and create the region?,and/or pass the variables to your game method to get it all setup?
//-----------------------
//yourGameMethod(pos1,pos2,player)
//-----------------------
player.sendMessage(ChatColor.GOLD + "Region created,have fun");
}
}
}
}
警告:根据您设置插件或触发事件的方式,此代码一次只能对一个玩家起作用。如果两个玩家同时使用它,那么他们的点击可能会混淆。要解决此问题,您需要将点击次数与播放器相关联,并将其存储在列表中,以便在许多玩家使用该插件时可以轻松地将它们进行匹配,并且可以包括超时功能,以将pos重置为0几分钟之内没有第二次点击。
,Integer pos = 0;
...
if (pos.equals(0)) {...}
您的静态Integer对象pos永不改变?!
编辑:看看:https://javatutorialhq.com/java/lang/integer-class-tutorial/