简体   繁体   English

在C#中生成随机装箱的坐标

[英]Generate random boxed co-ordinates in c#

I need to find random co-ordinates, bound like a square. 我需要找到一个像正方形一样的随机坐标。 For this I defined this where the values 70, 55, 175, 175 are the furthest points I want to go to: 为此,我定义了以下值:70、55、175、175是我想去的最远点:

north = Utility.generateRandomNumber(Utility.Directions.NORTH, 70);
south = Utility.generateRandomNumber(Utility.Directions.SOUTH, 55);
east = Utility.generateRandomNumber(Utility.Directions.EAST, 175);
west = Utility.generateRandomNumber(Utility.Directions.WEST, 175);

My generator is below, where I have declare a global static param: 我的生成器在下面,我在其中声明了全局静态参数:

public static Random random = new Random();

Directions is an enumerator. Directions是一个枚举器。

public static int generateRandomNumber(Directions direction, int to)
{
    if ((direction == Directions.SOUTH) || (direction == Directions.WEST))
        return random.Next(to * -1, 0);
    else
        return random.Next(0, to);
}

The function works fine and I retrieve co-ordinates like below: 该函数工作正常,我检索如下的坐标:

North: 52 South: -13 East: 82 West: -105
North: 27 South: -45 East: 172 West: -117
North: 0 South: -37 East: 161 West: -160
North: 43 South: -39 East: 26 West: -174
North: 29 South: -7 East: 75 West: -125
North: 19 South: -51 East: 93 West: -49
North: 28 South: -20 East: 26 West: -28

The issue is that the box is built around the (0,0,0,0) co-ordinate and I'm not sure how to get out of it whilst ensuring that North is greater than south, west is left to the map and east is right to the map. 问题是盒子是围绕(0,0,0,0)坐标构建的,我不确定如何摆脱它,同时确保北大于南,西留在地图上,东在地图上。

I would suggest you change your approach: 我建议您更改方法:

  • Generate a point for the North/West corner, anywhere in the appropriate range 在适当范围内的任何地方为北/西角生成一个点
  • Generate the width and height, ensuring they're positive 生成宽度和高度,确保它们是正的
  • Set East = West + Width, and South = North - Height 设置东=西+宽,南=北-高

Actually I solved it by randomizing also the zero coordinate. 实际上,我也通过随机化零坐标来解决它。 This way the "centre" point of the bound also moved around. 这样,边界的“中心”点也随之移动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM