CRYENGINE Game Development Blueprints
上QQ阅读APP看书,第一时间看更新

Shooting the player

Now that we have added player detection to our AI, it is ready to shoot at the player now. To accomplish this, we will need to use a method that gets called every n seconds so as to prevent shooting rapidly during every frame. Luckily, for the purposes of this book, I've created a lightweight callback timer that doesjust this. So let's get started.

Open the CPlayer.cpp file and navigate to the PostInit() method. Add a callback method to the timer that shoots the player. It should look similar to the following:

//We Are AI
if( !m_bClient )
{
  //Add Callback To Timer.  Try To Shoot The Player Every 2 Seconds.
  m_CallBackTimer += [ this ] ( double dDelta )
  {
    //Get The Player
    auto pPlayer = gEnv->pGame->GetIGameFramework()->GetClientActor();

    //Get The Distance The We Are From The Player/
    auto Len = GetEntity()->GetWorldPos().GetDistance( pPlayer->GetEntity()->GetWorldPos() );

    //If We Are Less Than 15 Meters, Then Shoot The Player.
    if( Len < 15 )
    {
      //Unlimited Ammo For AI.
      m_pWeapon->AddAmmo( 1 );

      //Shoot At The Target, With A Bullet Speed Multiplier Of 10.
      m_pWeapon->Shoot( 10 );
    }
  };
}

Notice how we first check to see if we are an AI. We then proceed to add a callback method in the form of a C++11 Lambda, which will get called every time the timer reaches its interval (which is currently set at 2 seconds). In the callback, we simply add ammo to the AI to give it unlimited ammunition and shoot the weapon.