Download

Replicate ApplyDamage on client

I have a projectile class, when it directly hits another player it calls the UGamplayStatics::ApplyDamage() function on the AActor. The issue I have it that I only have a pointer to the server-side AActor it hit, how do I then replicate this function call and tell the client which AActor it needs to call the ApplyDamage function for?

I had a look at the ShooterGame example, however they don’t have this issue as they are applying a radial damage, so they just call the ApplyRadialDamage function on the client and it will work out the correct actor.

Look into Remote Procedure Calls and the UFUNCTION specifiers associated with them (NetMulticast, Client, Server). Generally speaking, if you want to fire the function on the server and all connected clients, NetMulticast. If you want to fire the RPC on just the server, use Server. If you want to fire on just a specific Client, use Client. When calling functions on a specific client from the server, you’ll want to do so via that client’s PlayerController. The server has access to all the player controllers, and you can iterate through them in the following way:


for (FConstPlayerControllerIterator It = GetWorld()->GetPlayerControllerIterator(); It; ++It)
{
   // AMyPlayerControllerClass derives from APlayerController
   AMyPlayerControllerClass* PC = Cast<AMyPlayerControllerClass>(*It);

   // If the PC belongs to the client you want to execute on, call said Client function
}

Of course, depending on where the client function you want to call lives in your code (your classes that derive from APawn/ACharacter/AHUD/etc), you’ll need to get to these objects from the player controller. For example, if my Client RPC is called Foo() and lives in the ACharacter class of my game, I might call something like this inside of MyPlayerControllerClass:


void SomeFunctionInMyPlayerControllerClass()
{
   AMyCharacterClass* MyPawn = Cast<MyCharacterClass>(GetPawn());
   if (MyPawn)
   {
      MyPawn->Foo();
   }
}

I hope this helps.