-3

I am making a game and I have my hero and enemy. Now I want enemy to follow hero when distance between them is 400 for example. How can I make it work. Here is what I ve got so far, but it doe not work. Objects::calcAngle(Objects* obj) - calculates angle between central points of 2 objects.

float Objects::calcAngle(Objects* obj){
    float dx = obj->X - this->X; 
    float dy = obj->Y - this->Y;
    float angle=atan(dy/dx)*180/PI;
    return angle;
}

void Enemy::Attack(mainCar* car){
    float angle=0;
    angle=this->calcAngle(car);
    if(this->Distance(car)<400){
        this->attack=true;
        this->heading=this->calcAngle(car)+90; 
        this->Vtri=abs(this->Vtri);
    } else if (this->Distance(car)>400) {
        this->attack=false;
    }
}

Vtri is speed of movement. heading is direction in degrees.

If you can give me a link to where it is described or just tell me here, it would be great. I have 2 days to submitt my project.

4

1 回答 1

2

为了使对象从源点移动到目标点,您需要做一些事情:

  1. 当前位置 X 和 Y 坐标
  2. 目标位置 X 和 Y 坐标
  3. 从源头移动到目的地的攻角
  4. 从目的地移动到源头的速度

伪代码:

dy = PositionDestination.Y - PositionCurrent.Y
dx = PositionDestination.X - PositionCurrent.X
angle = atan2(dy/dx)

vx = v * cos(angle)
vy = v * sin(angle)

PositionCurrent += Vector(vx, vy)

C#:

 // angle is the arctan placed in the correct quadrant of the Y difference and X difference
 float angleOfAttack = 
      (float)Math.Atan2((double)(PositionDestination.Y - PositionCurrent.Y), 
      (double)(PositionDestination.X - PositionCurrent.X));

 // velocity is the cos(angle*speed), sin(angle*speed)
 Vector2 velocity = 
      new Vector2((float)Math.Cos(angleOfAttack) * projectileMoveSpeed,
      (float)Math.Sin(angleOfAttack) * projectileMoveSpeed);

 // new position is +velocity
 PositionCurrent += velocity;

因此,您首先根据源坐标和目标坐标获得角度。然后,您可以根据角度和速度获得速度方向和距离。最后,根据速度矢量将当前位置移动到新位置。

于 2012-04-22T20:59:00.800 回答