这个例子显示了如何在游戏世界中实现专属聊天,用于靠近彼此的用户。它通过使用 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