【问题标题】:How can I draw 50 of the same sprite in random locations in XNA?如何在 XNA 中的随机位置绘制 50 个相同的精灵?
【发布时间】:2012-03-15 08:17:43
【问题描述】:
我目前正在做一个学校项目,但错过了一堂课,老师解释了如何在没有大量代码的情况下做到这一点。
这是作业:
创建一个 XNA 应用程序会显示 50 个向下加速的动画精灵。当精灵碰到窗口底部时,让它反弹。在随机位置生成每个精灵,以使精灵始终完全在窗口中。将随机位置的 Y 分量限制在 0 到 300 之间。最后,使精灵在按下空格键时重置为其原始位置。
这是一个示例图片的链接,rep 不够高,无法插入图片
http://hypergrade.com/grader/file_download.php?id=132
我有一个单独的精灵绘制和动画,我只需要一些关于为相同的 Texture2D 随机生成位置的指导。
【问题讨论】:
标签:
random
xna
sprite
texture2d
【解决方案1】:
你应该使用 Random 类。
// Make one instance of random, the seed is the milliseconds, other way random always returns the same sequence of random numbers.
static readonly Random rnd = new Random(DateTime.Nom.Milliseconds);
List<Sprite> Sprites = new List<Sprite>(50);
public void Update()
{
//Add new sprites with a 90% or probability
if (Sprites.Count<50 && rnd.Next(100) > 90)
{
Sprite sprite = new Sprite();
// This X calculation makes the sprite not to get out of the screen at both sides
sprite.Pos.X = (float) ( (0.1f + 0.8f * rnd.NextDouble()) * GraphicsDevice.Viewport.Width);
sprite.Pos.Y = (float) ( rnd.NextDouble() * 300 );
Sprites.Add(Sprite);
}
}
当然 de Sprite 类取决于你.. :)