我正在使用Microsoft XNA制作一个简单的游戏,我有一个Enemy.cs
类,其中包含一个属性enemyMoveSpeed
。
public class Enemy
{
float enemyMoveSpeed { get; set }
}
在更新部分的Game1.cs
中,我放了一个定时器,可以不断更改以下属性。
protected override void Update(GameTime gameTime)
{
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
timer -= elapsed;
if (timer < 0)
{
foreach (Enemy E in enemies)
{
E.enemyMoveSpeed += 1;
}
timer = TIMER; //Reset Timer
}
}
变化后,每一个敌人的新实例都会受到影响。有人可以告诉我如何实现这个吗?
答案 0 :(得分:1)
创建一个列表
List<Enemy> MyEnemyList;
//of course you will have to add Enemies to this list somehow. Probably you already have a list or an array, wich behaves the same for this purpose.
foreach (Enemy E in MyEnemyList)
{
E.enemyMoveSpeed += 1; //if you are incrementing the speed of everyone by 1.
//or any other option you think is better
}
答案 1 :(得分:1)
为新速度使用静态属性,在你的Enemy构造函数中,你可以设置实例属性以匹配它。
像
这样的东西class Enemy
{
public static int NewEnemySpeed { get; set;}
public int Speed {get; set;}
public Enemy()
{
Speed = NewEnemySpeed;
}
}
从你的Game1.Update,你可以做到这一点
Enemy.NewEnemySpeed = ..//some new speed
答案 2 :(得分:0)
也许这样的事情可以帮助你。
public class Enemy
{
public Enemy()
{
EnemyState = new EnemyState { IsDirty = true, Position = Vector2.Zero };
Speed = 3.0f;
}
public EnemyState State { get; set }
public float Speed { get; set; }
}
public class EnemyState
{
public bool IsDirty { get; set }
public Vector2 Position { get; set; }
}
protected override void Update(GameTime gameTime)
{
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
// If should spawn enemy
// var enemy = new Enemy();
// enemy.State.Position = // TODO insert starting position
// enemies.Add(enemy);
// Find all enemies that should be moved
// Set IsDirty = true;
// Move each enemy that IsDirty
timer -= elapsed;
if (timer < 0)
{
foreach (Enemy enemy in enemies.Where(e => e.State.IsDirty))
{
enemy.State.Position.X += enemy.Speed;
enemy.State.IsDirty = false;
}
timer = TIMER; //Reset Timer
}
}