【发布时间】:2014-11-14 18:59:08
【问题描述】:
大家好,我正在尝试创建一个游戏,现在,我有一个气球类,我想通过一个数组创建一些气球类,然后绘制到游戏中。
但目前看来,它要么只创建一个气球实例,要么只绘制 1 个实例。我已经多次查看它,据我了解,它应该循环遍历整个数组大小(当前设置为 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的新实例,而是保留一个实例。有可能得到相同的种子,因此得到相同的值。 -
@TyCobb 获得相同的种子实际上非常普遍 - 种子完全基于系统时钟,因此同时创建的一系列
Random对象将返回完全相同的系列价值观。就个人而言,我认为这是一个巨大的设计缺陷。 -
如果您希望在每次应用运行时多一点随机,请使用
Random random = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);msdn.microsoft.com/en-us/library/ctssatww(v=vs.110).aspx