ตัวอย่างนี้แสดงวิธีการใช้งานการแชทสุดพิเศษสำหรับผู้ใช้ที่อยู่ใกล้กันในโลกเกมมันขยายการเรียกคืนด้วยฟังก์ชันที่ใช้ 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)
-- รับผู้เล่นที่เกี่ยวข้องกับรหัสผู้ใช้ที่กำหนด
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