大家好,我正在尝试创建一个游戏,现在,我有一个气球类,我现在想通过数组创建一定数量的气球,然后将其绘制到游戏中。
但是目前看来,它要么只是创建一个零件序号实例,要么仅绘制一个零件序号。我多次看过它,据我了解,它应该遍历整个数组大小(当前设置为10)并创建那么多气球,然后更新和绘制很多气球。
您无法使用阵列执行当前操作吗?我是否必须谨慎地创建每个对象?
这是有关两个类的代码。
游戏等级:
创建对象并绘制对象的类。
public partial class GameLevel : GameScreen
{
SpriteBatch spriteBatch;
protected Game game;
Texture2D balloonTexture;
Balloon[] balloons = new Balloon[10];
public GameLevel(Game game, SpriteBatch spriteBatch)
: base(game, spriteBatch)
{
this.game = game;
this.spriteBatch = spriteBatch;
}
public void LoadContent()
{
for (int i = 0; i < balloons.Length; i++)
{
int colour;
Random random = new Random();
colour = random.Next(1, 6);
switch (colour)
{
case 1: balloonTexture = Game.Content.Load<Texture2D>("Images/BlueBalloon");
break;
case 2: balloonTexture = Game.Content.Load<Texture2D>("Images/RedBalloon");
break;
case 3: balloonTexture = Game.Content.Load<Texture2D>("Images/YellowBalloon");
break;
case 4: balloonTexture = Game.Content.Load<Texture2D>("Images/GreenBalloon");
break;
case 5: balloonTexture = Game.Content.Load<Texture2D>("Images/PurpleBalloon");
break;
}
balloons[i] = new Balloon(new Rectangle(0, 0, 1152, 648), balloonTexture);
balloons[i].SetStartPosition();
}
}
public void Update()
{
for (int i = 0; i < balloons.Length; i++)
{
balloons[i].Update();
}
}
public override void Draw(GameTime gameTime)
{
for (int i = 0; i < balloons.Length; i++)
{
balloons[i].Draw(spriteBatch);
}
base.Draw(gameTime);
}
}
}
气球课:
public class Balloon
{
Vector2 position;
Vector2 motion;
Rectangle bounds;
Rectangle screenBounds;
public Texture2D texture;
float balloonSpeed = 4;
public Balloon(Rectangle screenBounds, Texture2D texture)
{
this.texture = texture;
this.screenBounds = screenBounds;
}
public Rectangle Bounds
{
get
{
bounds.X = (int)position.X;
bounds.Y = (int)position.Y;
return bounds;
}
}
public void Update()
{
position += motion * balloonSpeed;
}
private void CheckWallColision()
{
if (position.X < 0)
{
position.X = 0;
motion.X *= -1;
}
if (position.X + texture.Width > screenBounds.Width)
{
position.X = screenBounds.Width - texture.Width;
motion.X *= -1;
}
if (position.Y < 0)
{
position.Y = 0;
motion.Y *= -1;
}
if (position.Y + texture.Height > screenBounds.Height)
{
position.Y = screenBounds.Height - texture.Height;
motion.Y *= -1;
}
}
public void SetStartPosition()
{
Random rand = new Random();
motion = new Vector2(rand.Next(2, 6), -rand.Next(2, 6));
motion.Normalize();
position = new Vector2(rand.Next(100, 500), rand.Next(100, 500));
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, position, Color.White);
}
}
}
最佳答案
我相信发生这种情况的原因与Random
对象的工作方式有关。构造一个时,它将系统时钟用作其种子(从中将生成所有值)。这意味着,如果您同时生成多个Random
实例,则每个实例将返回相同的一系列值。如果将这些值用于位置,则每个对象中的每个对象都将具有相同的位置,并且会相互绘制。在您的情况下,由于它们的大小相同,因此看起来好像只绘制了一个。
要解决此问题,请创建Random
的单个实例,并在需要新职位时仅在该单个实例上使用Next()
。
就我个人而言,我认为这是一个非常重要的设计缺陷-直观地发现,同时创建的一系列Random
对象将以完全相同的方式“随机”出现。但是:这是一个很好的例子,说明C#和任何其他语言创建的“随机”值实际上将是伪随机的,而对于伪随机性,实现非常重要。