【问题标题】:Randomise x and y coordinates of an object in C# [duplicate]C#中对象的随机x和y坐标[重复]
【发布时间】:2020-03-27 14:39:53
【问题描述】:

我有两个类,一个名为 GameObjects.cs,它初始化一个对象及其 x 和 y 值,我的第二个类是 Program.cs,在此我想要一种方法来随机化每个对象的 x 和 y 坐标我运行代码的时间,即目前它是 (10, 10) 例如树对象。

游戏对象类

namespace objectRandom
{
    class GameObject
{
        public string Name { get; }
        public int X { get; }
        public int Y { get; }

    public GameObject(string name, int x, int y)
    {
        Name = name;
        X = x;
        Y = y;
    }

    public override string ToString()
    {
        return String.Format("Name: {0}, X: {1}, Y: {2}", Name, X, Y);
    }
}

程序类

namespace objectRandom
{
    class Program
    {
        static IEnumerable<GameObject> GenerateGameObjects(int mapWidth, int mapHeight)
        {
        List<GameObject> gameObjects = new List<GameObject>();

        gameObjects.Add(new GameObject("Tree", 10, 10));

        return gameObjects;
    }

    static void Main(string[] args)
    {

        foreach (GameObject gameObject in GenerateGameObjects(50, 50))
        {
            Console.WriteLine(gameObject);
        }
    }
}

【问题讨论】:

  • 你研究过 Random() 函数吗?
  • 好的,那么当使用 Random 类时会发生什么? “msdn C# random”形式的搜索将很有用,例如。
  • 你得到 x 和 y 之间的随机数(你在调用中定义 x 和 y)
  • 你试过什么...?你做了什么研究?这种问题在网上的答案相当丰富

标签: c#


【解决方案1】:

只需使用Random 类在您想要的范围内生成随机数:

var rnd = new Random();
int minX = 0, maxX= 1000, minY = 0, maxY = 1000;
gameObjects.Add(new GameObject("Tree", rnd.Next(minX, maxX + 1), rnd.Next(minY, maxY + 1)));

【讨论】:

  • 这有帮助!非常感谢。
  • @kartikey 不客气
猜你喜欢
  • 1970-01-01
  • 2013-11-09
  • 2014-02-14
  • 2023-02-16
  • 1970-01-01
  • 1970-01-01
  • 2011-02-24
  • 2015-06-05
  • 2010-11-03
相关资源
最近更新 更多