In this lesson, you will learn how to mask network latency by spawning "ghost" actors locally before the server confirms their creation.
When a player performs an action that results in a new actor (like throwing a grenade or placing a building), waiting for a round-trip RPC to the server creates a jarring delay. If the client waits for the server to acknowledge the spawn, the action feels sluggish. To achieve a "snappy" feel, we use Client-Side Prediction for Spawning.
The Ghost Actor Pattern
The core concept is to treat the client-side spawn as a visual placeholder. When the user inputs the command:
- Spawn Locally: The client immediately spawns a "Ghost" version of the actor. This actor is marked as non-replicated or set to a specific "local-only" state so it doesn't duplicate when the real actor arrives.
- Request Server: Simultaneously, the client sends an RPC to the server to perform the "authoritative" spawn.
- Reconcile: Once the server’s replicated actor arrives via
OnRep_Actor, the client hides or destroys the "Ghost" and swaps it for the authoritative one.
Implementation Strategy
To prevent duplicate visuals, your GhostActor should be identifiable. You might set a bIsGhost flag on the actor immediately after spawning it:
// Client-side input event
void AMyCharacter::FireProjectile() {
// 1. Immediate visual feedback
AGhostProjectile* Ghost = GetWorld()->SpawnActor<AGhostProjectile>(...);
Ghost->SetIsGhost(true);
// 2. Request authoritative spawn
Server_SpawnProjectile();
}
When the replicated AProjectile finally arrives, you must ensure the transition is seamless. If the ghost and the real actor are visually identical, you simply destroy the ghost and snap the real one to its position. If you use a unique identifier (like a Guid or ClientSequenceNumber) passed through the Server_SpawnProjectile RPC, you can verify that the incoming replicated actor matches the ghost that the client is currently expecting.
This approach keeps the game feeling instantaneous for the player while maintaining the server as the ultimate source of truth for gameplay logic.
Key Takeaway: By spawning a temporary "ghost" actor locally and swapping it with the server-replicated version upon arrival, you eliminate perceived input lag during object spawning.