我想知道如何制作AI,它可以在地图上平滑地走动(在窗口大小之间)。就像,如果AI达到了定义的地点,那么它会走到另一个地方。 这是我试过的,创建一个简单的2D AI C++
首先,我得到一个从0.0f到608.0f的随机浮点数,因为我的窗口大小是640,640。
void AIntelligence::GenRandom()
{
MapX = static_cast <float> (rand())/(static_cast <float> (RAND_MAX/608.0f));
MapY = MapX;
}
然后,我在精灵的当前位置传递给这个函数
void AIntelligence::RandomMove(float PosX, float PosY)
{
this->PosX = PosX;
this->PosY = PosY;
if (PosX == MapX || PosY == MapY) //If the current is the same as the generated random, then
{ generate it again.
GenRandom();
}
else
{
if (PosX < MapX || PosY < MapY) //If not then I see if the position less than the
{ generated and translate it.
this->PosX += 8.0f;
this->PosY += 8.0f;
}
else if (PosX > MapX || PosY > MapY)
{
this->PosX -= 8.0f;
this->PosY -= 8.0f;
}
else
this->PosX += 0.0f;
this->PosY += 0.0f;
}
}
在我的消息循环,这里是我如何调用该方法
while (GetMessage(&Msg, NULL, 0, 0))
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
Inputs->GetInput(); //Not related
Moving->RandomMove(PosX,PosY);
D3DXVECTOR2 SpritePos = D3DXVECTOR2(Moving->getPosX(), Moving->getPosY());
PosX = Moving->getPosX();
PosY = Moving->getPosY();
Graphic->ClearBegin(); //Begin the direct3d scene
Sprite->Begin(D3DXSPRITE_ALPHABLEND);
float Radian = D3DXToRadian(Rotation);
D3DXMatrixTransformation2D(&Mat, NULL, 0.0f, &SpriteScaling, &SpriteCenter, Radian, &SpritePos); // This is where the transformation is set.
Sprite->SetTransform(&Mat);
Sprite->Draw(Texture, NULL, NULL, NULL, D3DCOLOR_XRGB(255, 255, 255));
Sprite->End();
Graphic->EndPresent();
}
的精灵做移动但只能向右移动。一旦它达到相同的地点,它只会停留在那里,并震动......很抱歉,如果我的解释不够清楚或没有提供足够的信息需要。
嘿@emartel感谢这么很多有用的指南。由于我正在计算距离,是否可以使用'D3DXVECTOR2(x,y)'?我的意思是,我如何使用这些向量来翻译精灵? – Student 2014-12-07 08:36:50
@Student我会远离API矢量类,并使用我自己的。当你打电话给MoveToward时,你的翻译会发生,所以你应该没问题 – emartel 2014-12-07 19:45:55
好的。谢谢:D它已经正常工作了。 – Student 2014-12-07 20:47:26