[英]How can I use the random class in c# to generate a single random number (xna)
I am trying to generate a random number using the Random
class in c# to draw a texture. 我正在尝试使用c#中的
Random
类生成一个随机数以绘制纹理。 I'm trying to draw a texture to a random coordinate on the screen, but when I try to run the code below, the texture keeps moving around random spaces. 我试图在屏幕上将纹理绘制为随机坐标,但是当我尝试运行以下代码时,纹理将在随机空间中移动。 I need to draw it and have it stay in place.
我需要绘制它并使其保持在原位。
Random _Random = new Random();
private int MaxX;
private int MaxY; //screen height and width
public Texture2D hat;
//code to load in image
//draw code
spriteBatch.Begin();
int hatx = _Random.Next(1, MaxX);
int haty = _Random.Next(1, MaxY);
spriteBatch.Draw(hat, new Rectangle(hatx, haty, 80, 80), Color.White);
spriteBatch.End();
You need to make the calls to Random.Next
only once for your texture. 您只需为纹理调用一次
Random.Next
。 Currently, you are calling it for every draw operation. 当前,您正在为每个绘制操作调用它。
Random _Random = new Random();
private int MaxX;
private int MaxY; //screen height and width
public Texture2D hat;
//code to load in image
// make sure x and y are initialized only once before rendering loop
int x = _Random.Next(1, MaxX);
int y = _Random.Next(1, MaxY);
//draw code
spriteBatch.Begin();
int hatx = x;
int haty = y;
spriteBatch.Draw(hat, new Rectangle(hatx, haty, 80, 80), Color.White);
spriteBatch.End();
Problem is that every time draw function calls x and y numbers are changed. 问题是每次绘制函数调用x和y时,数字都会更改。 Because every time random number generates a new number.
因为每次随机数都会生成一个新数字。 So your texture will be moving to different places.
因此,您的纹理将移动到不同的位置。 What you need to do here is that make two class members X and Y, and on ContentLoad function you generate random numbers and fill X and Y value.
您需要做的是使两个类成员成为X和Y,然后在ContentLoad函数上生成随机数并填充X和Y值。 And in draw function Use class members X and Y instead of making new X and Y.
在绘图函数中,使用类成员X和Y代替新的X和Y。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.