我有一个会射出射弹的物体,我试图使用一个列表在火箭队中产生(射弹),所以我可以在它们与物体碰撞时删除它们。所以我先创建List<Rectangle> Rockets;
然后添加一个函数,让火箭产生并不断发射:
if (Time > 0.2)
{
Time = 0;
Rockets.Add(new Rectangle((int)Position.X, (int)Position.Y, rocketTexture.Width, rocketTexture.Height));
}
然后我尝试更新它们,以便它们通过做一个foreach在屏幕上移动:
foreach (Rectangle r in Rockets)
{
}
问题
这是我遇到困难的地方,我如何调用每个Rocket列表中的x和y值,以便我可以在屏幕上移动它?
我可能会想到这一点,并且有一种更简单的方法可以制造大量的射弹,并且当它们与某种方式发生碰撞或者当它们走得太远时让它们消失。
答案 0 :(得分:3)
在游戏开发中,你宁愿使用update()方法实现一个Rocket类,你可以通过一些speed_x和speed_y属性来移动火箭。然后,您将在主run()方法中通过调用Rocket.getRect()(或者只是一个.Rect属性来检查冲突,该属性可以在父类Entity中实现)。
话虽如此,我可能没有理解这个问题。
答案 1 :(得分:1)
这是一个代码示例,希望它有所帮助
class Rocket
{
int _life;
public Rocket(Vector2 position, Vector2 direction)
{
_position = position;
_direction = direction;
//life of rocket. Once it reaches zero the rocket is removed.
_life = 100;
}
Vector2 _position
public Vector2 Position
{
get
{
return _position;
}
}
Vector2 _velocity;
Vector2 Velocity
{
get
{
return _velocity;
}
}
public int Life
{
get
{
return _life;
}
}
public void Update(World world)
{
_life--;
_position += _velocity;
//could check for collisions here, eg:
foreach (Ship ship in world.Ships)
{
if (Intersects(ship))
{
//collision!
//destroy this rocket
_life = 0;
//damage the ship the rocket hit
ship.ApplyDamage(10);
return;
}
}
}
}
class Game
{
List<Rocket> _rockets = new List<Rocket>();
List<Rocket> _deadRockets = new List<Rocket>();
void Update(GameTime gameTime)
{
//.ToArray() is used here because the .net list does not allow items to be removed while iterating over it in a loop.
//But we want to remove rockets when they are dead. So .ToArray() means we are looping over the array not the
//list, so that means we are free to remove items from the list. basically it's a hack to make things simpler...
foreach (Rocket rocket in _rockets.ToArray())
{
//world is an object that contains references to everything on the map
//so that the rocket has access to that stuff as part of it's update
rocket.Update( world );
//if the rocket has run out of life then remove it from the list
if (rocket.Life <= 0)
_rockets.Remove(rocket);
}
}
void FireRocket(Vector2 from, Vector2 direction)
{
Rocket newRocket = new Rocket(from, direction);
_rockets.Add(newRocket);
}
}
答案 2 :(得分:0)
执行for
循环而不是foreach
循环。我还建议使用数组(并创建一个Rocket
类而不仅仅是Vector2s。)
for (int i = 0; i < Rockets.Count; i++)
{
Rockets[i] = new Rectangle(Rockets[i].X + 20, Rockets[i].Y + 20);
}