-3

我试图让我的敌人跟随玩家并在 20 像素内停止,我尝试了多种算法,包括 Vector2.Lerp(); 尝试解决此问题的方法,但它不断破坏构建。任何帮助将不胜感激。代码如下。

public void Update(GameTime gameTime)
{
    if (this.IsAlive)
    {
        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
        double distanceToPlayer = Math.Sqrt(Math.Pow(Level.Player.Position.X - this.Position.X, 2) + Math.Pow(Level.Player.Position.Y - this.Position.Y, 2));

        // Calculate tile position based on the side we are walking towards.
        float posX = Position.X + localBounds.Width / 2 * (int)direction;
        int tileX = (int)Math.Floor(posX / Tile.Width) - (int)direction;
        int tileY = (int)Math.Floor(Position.Y / Tile.Height);

        if (waitTime > 0)
        {
            // Wait for some amount of time.
            waitTime = Math.Max(0.0f, waitTime - (float)gameTime.ElapsedGameTime.TotalSeconds);
            if (waitTime <= 0.0f)
            {
                // Then turn around.
                direction = (FaceDirection)(-(int)direction);
            }
        }
        else
        {
            // If we are about to run into a wall or off a cliff, start waiting.
            if (Level.GetCollision(tileX + (int)direction, tileY - 1) == TileCollision.Impassable || Level.GetCollision(tileX + (int)direction, tileY) == TileCollision.Passable) //is the enemy is close and is not attacking, attack and turn!
            {
                waitTime = MaxWaitTime;
            }
            else
            {
                // Move in the current direction.
                Vector2 velocity = new Vector2((int)direction * MoveSpeed * elapsed, 0.0f);
                position = position + velocity;
            }
        }
        dtAttack += gameTime.ElapsedGameTime;
        AttackPlayer();
    }
    else
    {
        dt += gameTime.ElapsedGameTime;
        if (dt.TotalSeconds > (sprite.Animation.FrameCount * sprite.Animation.FrameTime))
            this.Remove = true;
    }
}
4

1 回答 1

1

屏幕上必须是20像素吗?似乎很奇怪。Vector2.Distance您可以尝试使用该方法计算玩家和敌人之间的欧几里得距离。如果距离为 20 或更低,则阻止敌人。如果没有,请继续关注玩家。

于 2012-12-18T19:19:24.197 回答