Detecting the player and preventing mobility

In order for the AI to shoot at the player, it needs to know where it is and how to aim at it. In this section, you will learn how to detect the player and make the AI aim at it:

Open the CPlayer.cpp file and navigate to the Update() method. Since the AI and player are sharing the same class, we need to branch the logic based on whether we are currently the AI or the player. If we are the AI, we need to aim our weapon at the player. It should look similar to the following:

//We Are AI
if( !m_bClient )
{
  //Get The Player.
  auto pPlayer = static_cast< CPlayer* >( gEnv->pGame->GetIGameFramework()->GetClientActor() );

  //Get The Direction We Would Need To Aim To Hit The Player.
  auto ShootDir = ( pPlayer->GetEntity()->GetWorldPos() - GetEntity()->GetWorldPos() ).normalized();

  //Get The Weapon's Entity.
  auto pWeaponEnt = m_pWeapon->GetEntity();
  if( pWeaponEnt )
  {
    //Point The Weapon At The Target.
    pWeaponEnt->SetRotation( quaternion::CreateRotationVDir( ShootDir ), ENTITY_XFORM_ROT );
  }

}

Notice that we get the direction the AI needs to aim at by getting the difference between the AI's position and the player's position. We then instruct the weapon to set its rotation to the direction that we calculated.

It is important for our game that the AI doesn't move around. Unfortunately, our Player class is set up to move when input is detected. To prevent the AI from moving, simply wrap the movement and rotation processing calls with an if statement. In the CPlayer class's Update() method, wrap the movement and rotation processing code with an if statement. It should look like this:

//Only Process Movement And Rotation If We Are NOT An AI (The Player).
if( m_bClient )
{
  //Process Player Movement.
  ProcessMovement( ctx.fFrameTime );

  //Process Player Rotation.
  ProcessRotation( ctx.fFrameTime );

}

Notice the m_bClient variable; it is the only variable that needs to be considered in order to detect between the player and AI.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.193.255