基於距離的聊天

*此內容是使用 AI(Beta 測試版)翻譯,可能含有錯誤。若要以英文檢視此頁面,請按一下這裡

這個範例展示了如何為在 3D 世界中相互接近的用戶實現獨佔聊天。它擴展了回調函數,使用 TextSource 來識別可能成為消息接收者的用戶位置。如果這個函數返回 false,意味著用戶的位置超出了預設的有效範圍,因此系統不會將消息傳遞給該用戶。

將以下內容添加到 Script 中的 ServerScriptService

Server

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
©2026 Roblox Corporation、Roblox、Roblox 標誌及 Powering Imagination 是我們在美國及其他國家地區的部分註冊與未註冊商標。