敌人侦测距离

时间:2015-06-23 15:00:45

标签: c# xna

我目前让我的敌人的行动在他们开始向敌人移动的地方工作但是我希望改变它只是在玩家进入敌人的某个距离之前向玩家移动所以我需要创建一些代码可以解决敌人的位置,如果他们在175像素范围内,敌人将开始移动。我不知道如何将其实现到我已有的代码中。

这是我的敌人运动代码:它使用trig计算到敌人的最短距离,然后将敌人物体推向玩家。一旦发生碰撞,玩家就会被移除。

class Enemy : Obj
{
    float spd = 1;
    float detectionDistance = 175;

    public Enemy(Vector2 pos)
        : base(pos)
    {
        position = pos;
        spriteName = "BlackBall";
        speed = spd;
    }

    public override void Update()
    {
        rotation = point_direction(position.X, position.Y, Player.player.position.X, Player.player.position.Y);
        speed = spd;

        base.Update();
    }

    public override void pushTo(float pix, float dir)
    {
        float newX = (float)Math.Cos(MathHelper.ToRadians(dir));
        float newY = (float)Math.Sin(MathHelper.ToRadians(dir));
        newX *= pix;
        newY *= pix;
        if (!Collision(new Vector2(newX, newY), new Player(Vector2.Zero)))
        {
            base.pushTo(pix, dir);
        }
    }

    //Uses Trig to calculate the shortest distance to the player then moves towards that position
    private float point_direction(float x, float y, float x2, float y2)
    {
        float diffx = x - x2;
        float diffy = y - y2;
        float adj = diffx;
        float opp = diffy;
        float tan = opp / adj;
        float res = MathHelper.ToDegrees((float)Math.Atan2(opp, adj));
        res = (res - 180) % 360;
        if (res < 0) { res += 360; }
        return res;
    }

2 个答案:

答案 0 :(得分:0)

  public override void Update()
{
    rotation = point_direction(position.X, position.Y, Player.player.position.X, Player.player.position.Y);
    distance = sqrt(xdiff^2 + ydiff^2) <-- This line is pseudo-code
    if(distance<detectionDistance)
    {
        speed = spd;
    } 
    else
    {
        speed = 0
    }

    base.Update();
}

答案 1 :(得分:0)

使用距离公式并检查玩家位置是否在175个单位内。

public override void Update()
{
    rotation = point_direction(position.X, position.Y, Player.player.position.X, Player.player.position.Y);
    speed = Math.Sqrt(Math.Pow(Math.Abs(Player.player.position.X - position.X), 2.0) + Math.Pow(Math.Abs(Player.player.position.Y - position.Y), 2.0))) <= 175 ? spd : 0;

    base.Update();
}