Skip to content

Instantly share code, notes, and snippets.

@howmanysmall
Created December 6, 2020 02:36
Show Gist options
  • Save howmanysmall/38f4059fc4712be87157832cdff56aa6 to your computer and use it in GitHub Desktop.
Save howmanysmall/38f4059fc4712be87157832cdff56aa6 to your computer and use it in GitHub Desktop.
local Players = game:GetService("Players")
local CollectionService = game:GetService("CollectionService")
local RunService = game:GetService("RunService")
local CatchFactory = require("CatchFactory")
local Constants = require("Constants")
local GroupPromise = require("GroupPromise")
local Promise = require("Promise")
local PromiseChild = require("PromiseChild") -- Basically Promisified WaitForChild
local CustomerSpawns = CollectionService:GetTagged("CustomerSpawns")
local StaffSpawns = CollectionService:GetTagged("StaffSpawns")
local CustomerLength = #CustomerSpawns
local StaffLength = #StaffSpawns
local RandomLib = Random.new(tick() % 1 * 1E7)
local RAISED_VECTOR3 = Vector3.new(0, 4, 0)
local MAX_SPAWN_ATTEMPTS = 10
local function SpawnAtLocation(Character: Model, HumanoidRootPart: Part, GoalPosition: CFrame)
local Attempts = 0
HumanoidRootPart.Anchored = true
repeat
Attempts += 1
Character:SetPrimaryPartCFrame(GoalPosition)
until Character:GetPrimaryPartCFrame() == GoalPosition or Attempts > MAX_SPAWN_ATTEMPTS or not RunService.Heartbeat:Wait()
HumanoidRootPart.Anchored = false
return Attempts > MAX_SPAWN_ATTEMPTS
end
local function CharacterAddedFenv(Player: Player)
return function(Character: Model)
CollectionService:AddTag(Character, "SpawnReady")
local Promises = table.create(2)
Promises[1] = GroupPromise.PromiseRankInGroup(Player, Constants.CONFIGURATION.GROUP_ID)
Promises[2] = PromiseChild(Character, "HumanoidRootPart", 5)
Promise.All(Promises):Spread(function(RankInGroup, HumanoidRootPart)
if RankInGroup >= Constants.CONFIGURATION.MINIMUM_RANK_FOR_STAFF_SPAWN then
local GoalPosition: CFrame = CFrame.new(StaffSpawns[RandomLib:NextInteger(1, StaffLength)].Position + RAISED_VECTOR3)
SpawnAtLocation(Character, HumanoidRootPart, GoalPosition)
else
local GoalPosition: CFrame = CFrame.new(CustomerSpawns[RandomLib:NextInteger(1, CustomerLength)].Position + RAISED_VECTOR3)
SpawnAtLocation(Character, HumanoidRootPart, GoalPosition)
end
end):Catch(CatchFactory("Promise.All(Promises)"))
end
end
local function PlayerAdded(Player: Player)
CollectionService:AddTag(Player, "SpawnConnected")
local CharacterAdded = CharacterAddedFenv(Player)
Player.CharacterAdded:Connect(CharacterAdded)
if Player.Character and not CollectionService:HasTag(Player.Character, "SpawnReady") then
CharacterAdded(Player.Character)
end
end
Players.PlayerAdded:Connect(PlayerAdded)
for _, Player in ipairs(Players:GetPlayers()) do
if not CollectionService:HasTag(Player, "SpawnConnected") then
PlayerAdded(Player)
end
end
return false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment