gpt4 book ai didi

c# - 如何在随机位置绘制单个 Sprite 10 次?

转载 作者:太空狗 更新时间:2023-10-29 21:18:29 25 4
gpt4 key购买 nike

我对此完全陌生,有一个问题。我在学校和家里都做过练习,但我不知道该怎么做。

问题是我想在屏幕上的 10 个随机位置绘制一个 Sprite ,而不使用特殊的 Sprite 类。我的问题是它们在绘制后又消失了。

解决了,感谢大家的帮助!

public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;

Texture2D turtleTexture;
int counter = 0;
Random randomera = new Random();
int x;
int y;

public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}

protected override void Initialize()
{
base.Initialize();
}

/// <summary>
/// </summary>
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
turtleTexture = Content.Load<Texture2D>(@"Images/turtle_50x38");
}

protected override void UnloadContent()
{
}

protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();

/*
if(counter < 10)
{
x = randomera.Next(600);
y = randomera.Next(400);
counter++;
}
*/

base.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.White);

spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);


if (counter < 10)
{
for (int i = 0; i < 10; i++)
{
spriteBatch.Draw(turtleTexture, new Vector2(randomera.Next(600), randomera.Next(400)),
Color.Black);
counter++;
}
}

spriteBatch.End();
base.Draw(gameTime);
}
}

最佳答案

如果你想让你的 Sprite 一直在相同的随机位置并且仍然清除你的视口(viewport)(例如,你可能想要渲染其他内容)你可以将每帧的随机种子重置为相同的值:

protected override void Draw(GameTime gameTime)
{
randomera = new Random(seed);
GraphicsDevice.Clear(Color.White);

spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);


if (counter < 10)
{
for (int i = 0; i < 10; i++)
{
spriteBatch.Draw(turtleTexture, new Vector2(randomera.Next(600), randomera.Next(400)),
Color.Black);
counter++;
}
}

spriteBatch.End();
base.Draw(gameTime);
}

种子应在您的 Initialize() 方法中随机生成,之后不得更改。

您也可以只使用预定义的坐标初始化列表:

List<Vector2> coords = Enumerable.Range(0, 10).Select(i => new Vector2(randomera.Next(600), randomera.Next(400)).ToList();

并在您的绘图例程中使用此列表:

for (int i = 0; i < 10; i++)
{
spriteBatch.Draw(turtleTexture, coords[i],
Color.Black);
}

关于c# - 如何在随机位置绘制单个 Sprite 10 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12394520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com