我的小行星在我的游戏中产生了一个定时器,当它们产卵时我希望它们一次产生一个。我的问题是它们都在同一行中产生,所以当它们增加速度时,就会产生已经几乎离开屏幕的小行星这就是它的样子。
http://www.youtube.com/watch?v=9pKXZyzIpGs&feature=youtu.be
这是我的更新代码。
namespace PixeBlastGame
{
public class GameUpdate
{
SpriteBatch spriteBatch;
GameTime gameTime;
Vector2 vPlayer = new Vector2(0, 720 / 2);
Vector2 vAsteroid;
Vector2 velocity;
Random rand = new Random();
float spawnTimer;
float spawnRate = 1;
List<Vector2> Asteroids = new List<Vector2>();
public GameUpdate()
{
vAsteroid.Y = rand.Next(100, 680);
vAsteroid.X = 1100;
}
public void Update(GameTime theTime)
{
gameTime = theTime;
vPlayer.Y += velocity.Y;
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
spawnTimer += elapsed;
if (spawnTimer >= spawnRate)
{
Asteroids.Add(new Vector2(1000 ,rand.Next(0, 720)));
spawnTimer = 0;
}
if (Keyboard.GetState().IsKeyDown(Keys.Down))
{
velocity.Y = 5;
}
else if (Keyboard.GetState().IsKeyDown(Keys.Up))
{
velocity.Y = -5;
}
else
{
velocity.Y = 0;
}
if (vPlayer.Y > 630 )//+ Game1.tPlayer.Height)
vPlayer.Y = 630;
if (vPlayer.Y < -10) //+ Game1.tPlayer.Height)
vPlayer.Y = -10;
}
public void Draw(SpriteBatch theBatch)
{
spriteBatch = theBatch;
foreach (Vector2 asteroid in Asteroids) //Draw each astroid
{
DrawAsteroid(asteroid.X, asteroid.Y);
}
spriteBatch.Begin();
spriteBatch.Draw(Game1.tPlayer, vPlayer, Color.White);
spriteBatch.End();
}
public void DrawAsteroid(float x, float y)
{
vAsteroid.X -= 5; vAsteroid.Y = y;
spriteBatch.Begin();
spriteBatch.Draw(Game1.tAsteroid, vAsteroid, Color.White);
spriteBatch.End();
}
}
}
如果您需要更多代码来帮助我,请发表评论。
答案 0 :(得分:2)
制作小行星类
public class Asteroid
{
public Vector2 Velocity;
public Vector2 Position;
public Asteroid(Vector2 velocity, vector2 position)
{
Velocity = velocity;
Position = position;
}
}
现在将您的列表更改为:
List<Asteroid> Asteroids = ...
从现在开始,你可以做这样的事情
Asteroids[0].Velocity = Whatever
这样您就可以修改小行星的实例
现在看看你的绘制方法,
public void DrawAsteroid(float x, float y)
{
vAsteroid.X -= 5; vAsteroid.Y = y;
spriteBatch.Begin();
spriteBatch.Draw(Game1.tAsteroid, vAsteroid, Color.White);
spriteBatch.End();
}
你甚至没有使用x和y值,那么重点是什么?现在代码中的每个地方都必须删除vASteroid并使用列表中的实例!
将DrawAsteroid
更改为:
public void DrawAsteroid(Asteroid a)
{
spriteBatch.Begin();
spriteBatch.Draw(Game1.tAsteroid, a.Position, Color.White);
spriteBatch.End();
}
并致电它......
foreach (Asteroid a in Asteroids) //Draw each astroid
{
DrawAsteroid(a);
}
现在我们需要在更新中执行相同的操作,不要在Draw()
在更新中添加:
foreach (Asteroid a in Asteroids) //Update each astroid
{
UpdateAsteroid(a, elapsed);
}
并添加新方法......
public void UpdateAsteroid(Asteroid a, float elapsed)
{
a.Position += a.Velocity * elapsed;
}
现在,当你产生一颗小行星时,你需要确保你已经添加了速度!
Asteroids.Add(new Asteroid(new Vector2(0,-10), new Vector2(50,50)));
这将产生一个小行星,其Y 速度为-10,位置为50,50