Back to portfolio

In-Game Multiplayer Chat

Status
Completed
Engine
Unreal Engine
Languages
C++, Blueprint

An Unreal Engine multiplayer chat prototype connecting C++ RPCs and delegates to a UMG interface. I built the message flow and chat widgets on the C++ third-person sample; the character controls come from that template. The source code and the implementation walkthrough below show how a message travels from input to every player’s chat UI.

C++ RPC ve delegate yapısını UMG arayüzüne bağlayan bir Unreal Engine çok oyunculu sohbet prototipi. Mesaj akışını ve sohbet widget’larını C++ üçüncü şahıs örneği üzerine geliştirdim; karakter kontrolleri bu şablondan geliyor. Aşağıdaki kaynak kodu ve uygulama açıklaması, bir mesajın girişten tüm oyuncuların sohbet arayüzüne nasıl ulaştığını gösteriyor.

You can review and download this project on GitHub!

Bu projeyi GitHub'da inceleyip indirebilirsin!

Two players chatting in the multiplayer chat project

There are three Widget Blueprints derived from C++ classes.

C++ sınıflarından türetilmiş 3 widget Blueprint'i var.

WBP_MainHUD widget
Figure 1: WBP_MainHUD - The widget added to each player's screen. It contains the chat box.
Şekil 1: WBP_MainHUD - Oyuncuların ekranına eklenen ve sohbet kutusunu içeren widget.
WBP_Chatbox widget
Figure 2: WBP_Chatbox - The widget that displays chat messages. I used an EditableText for message input and a ScrollBox to display the messages.
Şekil 2: WBP_Chatbox - Mesaj metinlerinin eklendiği widget. Metin yazmak için bir EditableText, mesajları eklemek için bir ScrollBox kullandım.
WBP_ChatMessage widget
Figure 3: WBP_ChatMessage - The widget created and added to the chat box when a message is sent. It contains three text elements in a Horizontal Box.
Şekil 3: WBP_ChatMessage - Mesaj gönderildiğinde oluşturulup Chatbox'a eklenen widget. Horizontal box içinde 3 metin var.
Sender text color logic in WBP_ChatMessage
Figure 4: WBP_ChatMessage - The color of the sender text depends on who sent the message.
Şekil 4: WBP_ChatMessage - Gönderen metninin rengi, mesajı gönderen kişiye göre değişir.

There are three classes derived from UserWidget for sending and displaying messages: UMCChatMessage, UMCChatWidget, and UMCMainWidget.

Mesaj göndermek ve okumak için UserWidget'tan türeyen 3 sınıfımız var. Bunlar: UMCChatMessage, UMCChatWidget ve UMCMainWidget.

WBP_MainHUD widget
Figure 1: WBP_MainHUD

When a player joins the game, a widget is created from the UMCMainWidget class and added to the screen. This widget contains a UMCChatWidget.

Bir oyuncu oyuna girdiğinde UMCMainWidget sınıfından bir widget oluşturulup ekrana eklenir. Bu sınıf UMCChatWidget'ı içerir.


void AMultiplayerChatCharacter::BeginPlay()
{
    Super::BeginPlay();
                                
    if(IsLocallyControlled() && IsValid(MainWidgetClass))
    {
        MainWidget = CreateWidget<UMCMainWidget>(GetWorld(), MainWidgetClass);
        if(MainWidget)
        {
            MainWidget->AddToViewport();
        }
    }
}

When the player presses the Enter key, the StartTyping() method on this widget is called. It calls methods that prepare the interface for typing: setting the input mode to UI, dimming the background, and focusing the text input field.

Oyuncu Enter tuşuna bastığında bu widget içindeki StartTyping metodu çağrılır. Bu fonksiyon, input modunu UI olarak ayarlamak, arka planı karartmak, metin kutusuna odaklanmak gibi yazmayı mümkün kılan metotları çağırır.


void UMCMainWidget::StartTyping(APlayerController* PlayerController)
{
    if(ChatWidget)
    {
        ChatWidget->SetVisibility(ESlateVisibility::Visible);
        const FLinearColor SemiTransparentBlackColor = FLinearColor(0.f, 0.f, 0.f, 0.5f);
        GetChatWidget()->BackgroundBorder->SetBrushColor(SemiTransparentBlackColor);
        UWidgetBlueprintLibrary::SetInputMode_UIOnlyEx(PlayerController, ChatWidget->EnterTextWidget, EMouseLockMode::LockAlways);
        ChatWidget->EnterTextWidget->SetFocus();
        PlayerController->SetShowMouseCursor(false);
    }
}

When the chat box is active, pressing Enter calls the function bound to the EditableText's OnTextCommitted event. This function broadcasts the delegate that MainWidget is bound to, passing the message and the sender's name as parameters.

Sohbet kutusu aktifken Enter'a basılırsa, bu sefer EditableText'in OnTextCommitted event'ine bağlı fonksiyonum çalışır. Bu fonksiyon, MainWidget'ın bağlı olduğu delegate'i broadcast eder ve mesajı ve gönderenin adını parametre olarak gönderir.


void UMCChatWidget::EnterTextCommitted(const FText& Text, ETextCommit::Type CommitMethod)
{
    if(CommitMethod == ETextCommit::OnEnter)
    {
        if(Text.IsEmpty())
        {
            HideChatWidget();
        }
    
        else
        {
            const FString Sender = GetOwningPlayer()->GetPlayerState<APlayerState>()->GetPlayerName();
            const FChatMessageData MessageData(Sender, Text);
            OnMultiplayerChatMessageSent.Broadcast(MessageData);
            EnterTextWidget->SetText(FText::GetEmpty());
            HideChatWidget();
        }
    }
}

MainWidget uses GetOwningPawn() to access its owning character and calls AddChatText() on it. That function calls Server_AddChatText(), which runs on the server and invokes the multicast function MC_AddChatText(). The chat system is therefore multicast-based: MC_AddChatText() runs on the server and all clients, creating a message widget and adding it to each player's chat widget.

MainWidget, GetOwningPawn fonksiyonuyla ait olduğu karakter üzerindeki AddChatText fonksiyonunu çağırır. Bu fonksiyon sunucuda çalışan Server_AddChatText fonksiyonunu çağırır, o da multicast MC_AddChatText fonksiyonunu çağırır. Yani kurduğum mesajlaşma sistemi multicast tabanlı. Sunucuda ve tüm client'larda çalışır ve herkesin ekranındaki widget'a yeni bir mesaj widget'ı oluşturulup eklenmesini sağlar.


void AMultiplayerChatCharacter::AddChatText(const FChatMessageData& MessageData)
{
    Server_AddChatText(MessageData);
}
    
void AMultiplayerChatCharacter::Server_AddChatText_Implementation(const FChatMessageData& MessageData)
{
    MC_AddChatText(MessageData);
}
    
void AMultiplayerChatCharacter::MC_AddChatText_Implementation(const FChatMessageData& MessageData)
{
    TArray<UUserWidget*> FoundedWidgets;
    UWidgetBlueprintLibrary::GetAllWidgetsOfClass(this, FoundedWidgets, MainWidgetClass);
    TArray<UMCMainWidget*> MainWidgets;
    for(UUserWidget* NextWidget : FoundedWidgets)
    {
        if(UMCMainWidget* MainWidgetToAdd = Cast<UMCMainWidget>(NextWidget))
        {
            MainWidgets.Add(MainWidgetToAdd);
        }
    }
    
    UMCChatMessage* ChatMessage = CreateWidget<UMCChatMessage>(GetWorld(), ChatMessageClass);
    if(ChatMessage)
    {
        ChatMessage->SenderNameText->SetText(FText::FromString(MessageData.SenderName));
        ChatMessage->SenderMessage->SetText(MessageData.ChatMessage);
    }
        
    for(UMCMainWidget* NextMainWidget : MainWidgets)
    {
        NextMainWidget->GetChatWidget()->ChatMessages->AddChild(ChatMessage);
        NextMainWidget->GetChatWidget()->SetVisibility(ESlateVisibility::Visible);
        NextMainWidget->GetChatWidget()->ChatMessages->ScrollToEnd();
    }
}

Back to portfolio