這個例子顯示如何在遊戲世界中實現專屬聊天,用於靠近對方的用戶。它使用 TextSource 來擴展回調以識別可能是潛在訊息接收者的使用者位置。如果此功能返回 false,則表示使用者從訊息發送者的預設有效範圍範圍外找到資訊,因此系統不會將訊息傳送給該使用者。
在 Script 中添加以下內容到 ServerScriptService :
服務器
local TextChatService = game:GetService("TextChatService")
local Players = game:GetService("Players")
-- 取得基於位置的聊天頻道
-- 您可以將此一般通道替換為專用通頻道
local generalChannel: TextChannel = TextChatService:WaitForChild("TextChannels").RBXGeneral
-- 取得使用者角色位置的功能
local function getPositionFromUserId(userId: number)
-- 取得與給定使用者ID相關的玩家
local targetPlayer = Players:GetPlayerByUserId(userId)
-- 如果玩家存在,取得其角色的位置
if targetPlayer then
local targetCharacter = targetPlayer.Character
if targetCharacter then
return targetCharacter:GetPivot().Position
end
end
-- 如果找不到玩家或角色,返回預設位置
return Vector3.zero
end
-- 設置通用通道的回叫來控制訊息傳送
generalChannel.ShouldDeliverCallback = function(textChatMessage: TextChatMessage, targetTextSource: TextSource)
-- 取得訊息發送者和目標的位置
local sourcePos = getPositionFromUserId(textChatMessage.TextSource.UserId)
local targetPos = getPositionFromUserId(targetTextSource.UserId)
-- 如果發送者和目標之間的距離小於 50 單位,傳送訊息
return (targetPos - sourcePos).Magnitude < 50
end