有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java两点之间的随机位置(x1、z1、x2、z2)

我正在为Minecraft服务器制作一个插件,让玩家选择两个位置(x1,z1(第一个位置):x2,z2(第二个位置)),并允许他们在两个点之间设置这个区域(矩形/正方形),以便随机将它们传送到给定位置的任何位置

为了简单起见,我将省略大部分代码,只给出我遇到问题的部分。下面的代码将(在玩家加入服务器时)将他们传送到该区域内

我在nextInt()中设置了一些虚拟数据,以便您能够理解数学

Location 1 (x1, z1): -424, 2888
Location 2 (x2, z2): 4248, 3016

以上是以下程序段中的位置。(将“z”想象为图形上的“y”)

@EventHandler
    public void onPlayerJoin(PlayerJoinEvent event){
        Player player = event.getPlayer();

        int x = 0, y = 0, z = 0;
        Random randLocation = new Random();

        player.sendMessage(ChatColor.RED + "TELEPORTING TO WASTELAND..");

        x = randLocation.nextInt(((2888 - 424) + 1) + 424);
        z = randLocation.nextInt(((4248 - 3016) + 1) + 3016);
        Location location = player.getLocation();
            location.setX(x);
            location.setZ(z);
            location.setY(player.getWorld().getHighestBlockAt(x, z).getY());
        player.teleport(location);
}

问题是,有时一个(或两个)位置具有负值。我尝试了很多不同的方法来计算这些数字,但是我被难住了

问题: 有没有办法让Java在两个给定值之间选择一个随机数

例如:

randomLocation.nextInt(x1, x2);
randomLocation.nextInt(z1, z2);

共 (2) 个答案

  1. # 1 楼答案

    确定随机坐标的代码有错误:

    x = randLocation.nextInt(((2888 - 424) + 1) + 424);
    z = randLocation.nextInt(((4248 - 3016) + 1) + 3016);  
    

    您正在使用x1z1确定新的x位置,此时您应该使用x1x2

    randX = randLocation.nextInt(Math.abs(x2-x1) + 1) + Math.min(x1,x2);
    randZ = randLocation.nextInt(Math.abs(z2-z1) + 1) + Math.min(z1,z2);
    
  2. # 2 楼答案

    x = randLocation.nextInt((2888 - 424) + 1) + 424;
    z = randLocation.nextInt((4248 - 3016) + 1) + 3016;
    

    还有一件事:它应该是这样的:假设x2>;x1和z2>;z1

    x = randLocation.nextInt((x2 - x1) + 1) + x1;
    z = randLocation.nextInt((z2 - z1) + 1) + z1;