开发者

When an 'enemy' hits a waypoint, all the enemies go to the next waypoint in the queue... Why?

Here is the code I'm working on, I want all the enemies to go to each waypoint on their own accord; however, when one enemy hits the waypoint, all the enemies go to the next waypoint. How do I fix it?

I am running this from main, I have an enemy class and I have passed the queue in as a parameter when my enemy gets created. The original queue is called 'wayQ', the copied one that my enemies use is called 'way'.

Edit: Here is the enemy class. I modified the code to overide the main update method.

class Enemy : GameObject
{
    public Texture2D texture;
    public float scale = 0.3f;
    public Queue<Vector2> way = new Queue<Vector2>();
    private int atDestinationLimit = 1;

    public Enemy()
    {
    }

    public Enemy(ContentManager Content, int health, float speed, Vector2 vel, Vector2 pos, Queue<Vector2> wayQ)
    {
        this.Health = health;
        this.Speed = speed;
        this.velocity = vel;
        this.position = pos;
        this.IsAlive = true;
        this.texture = Content.Load <Texture2D>("SquareGuy");
        this.center = new Vector2(((this.texture.Width * this.scale) / 2), ((this.texture.Height * this.scale) / 2));
        this.centPos = this.position + this.center;
        this.way = wayQ;
    }

    public void Update(GameTime theGameTime)
    {
        if (way.Count > 0)
        {
            if (Vector2.Distance(centPos, way.Peek开发者_开发技巧()) < atDestinationLimit)
            {
                float distanceX = MathHelper.Distance(centPos.X, way.Peek().X);
                float distanceY = MathHelper.Distance(centPos.Y, way.Peek().Y);

                centPos = Vector2.Add(centPos, new Vector2(distanceX, distanceY));
                way.Dequeue();
            }
            else
            {
                Vector2 direction = -(centPos - way.Peek());
                direction.Normalize();
                velocity = Vector2.Multiply(direction, Speed);

                centPos += velocity;
            }
        }
    }
}


Modify your Enemy class to have its own copy of the waypoint list. Creating a waypoint list and assigning it to each Enemy object gives each Enemy object a reference to one list. When you Dequeue a waypoint, you do so in the one list.


Kinda difficult to see without the code used by said enemies (which seem to contain the waypoint logic). Logic states that the waypoints for one enemy seem to be shared amongst all enemies - is the enemy.way field perhaps declared static?


I changed the following code:

 this.way = wayQ;

to:

this.way = new Queue<Vector2>(wayQ);

Now it works great!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜