write luau code that will run in server, if some player chatted /spawn it will respawn him instantly, and then after respawned it will spawn 4 parts floating with hrp + Y vector3 5 coord smoothly like pets in some pet simulator game. The parts will change colors like rainbow smoothly and orbit. There will be a command "/change" and there will be 2 modes, first mode will be normal orbit, the second mode is the parts will still be hrp + Y vector3 5 coord is the parts will look where im looking ( look vector ).
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Of course! Here is a complete, server-side Luau script that accomplishes everything you've requested.
Instructions
Create a Script inside ServerScriptService in the Explorer.
Paste the entire code below into that script.
Run the game. You can now test the commands in the chat.
The Code
lua
--[[
Author: Your Name/AI
Description: Manages player commands for spawning and controlling cosmetic "pet" parts.
Commands:
- /spawn: Respawns the player and creates 4 orbiting, rainbow-colored parts around them.
- /change: Toggles the behavior of the parts between orbiting and matching the player's look direction.
]]
-- Services
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local ServerStorage = game:GetService("ServerStorage")
-- Configuration
local CONFIG = {
PART_COUNT = 4,
VERTICAL_OFFSET = 5, -- How high above the player's head the parts float
ORBIT_RADIUS = 4, -- The radius of the orbit circle
ORBIT_SPEED = 2, -- How fast the parts orbit (in radians per second)
RAINBOW_SPEED = 0.2, -- How fast the colors cycle (0 to 1)
PART_SIZE = Vector3.new(1.5, 1.5, 1.5),
PART_SHAPE = Enum.PartType.Ball
}
-- A table to store data for each player, like their parts and current mode.
local playerData = {}
-- A container to hold all the created parts for organization
local partsContainer = Instance.new("Folder")
partsContainer.Name = "OrbitingPartsContainer"
partsContainer.Parent = workspace
--================--
-- HELPER FUNCTIONS
--================--
-- Function to clean up a player's parts and data
local function cleanupPlayer(player)
local data = playerData[player]
if data and data.parts then
for _, part in ipairs(data.parts) do
part:Destroy()
end
end
playerData[player] = nil -- Clear the player's data from our table
end
-- Function to create the parts for a player
local function createOrbitingParts(player)
local character = player.Character
if not character then return end
-- First, ensure any old parts are gone
cleanupPlayer(player)
-- Initialize the data table for this player
playerData[player] = {
parts = {},
mode = "orbit", -- "orbit" or "look"
orbitAngle = 0 -- Starting angle for the orbit calculation
}
-- Create the parts
for i = 1, CONFIG.PART_COUNT do
local part = Instance.new("Part")
part.Name = player.Name .. "_OrbitPart_" .. i
part.Size = CONFIG.PART_SIZE
part.Shape = CONFIG.PART_SHAPE
part.Anchored = true
part.CanCollide = false
part.TopSurface = Enum.SurfaceType.Smooth
part.BottomSurface = Enum.SurfaceType.Smooth
part.Material = Enum.Material.Neon
part.Parent = partsContainer
table.insert(playerData[player].parts, part)
end
end
--================--
-- EVENT HANDLERS
--================--
-- Handle player commands via chat
local function onPlayerChatted(player, message)
local lowerMessage = string.lower(message)
-- Spawn command
if lowerMessage == "/spawn" then
-- A flag to ensure parts are created on the *next* respawn
playerData[player] = playerData[player] or {}
playerData[player].needsPartsOnSpawn = true
player:LoadCharacter() -- This respawns the player
-- Change mode command
elseif lowerMessage == "/change" then
local data = playerData[player]
if data and data.parts then
if data.mode == "orbit" then
data.mode = "look"
else
data.mode = "orbit"
end
-- Optional: Give feedback to the player
-- This requires a more complex setup to avoid chat spam, but for a simple case:
-- game.StarterGui:SetCore("ChatMakeSystemMessage", { ... }) would be better on the client.
-- For server simplicity, we'll just change the mode. The player will see the effect.
end
end
end
-- When a character is added (happens on join and respawn)
local function onCharacterAdded(player, character)
-- Check if this respawn was triggered by our /spawn command
local data = playerData[player]
if data and data.needsPartsOnSpawn then
data.needsPartsOnSpawn = nil -- Reset the flag
-- Wait a brief moment for the character to be fully set up
task.wait(0.1)
createOrbitingParts(player)
end
end
-- Set up events for new players
local function onPlayerAdded(player)
player.Chatted:Connect(function(message)
onPlayerChatted(player, message)
end)
-- We connect this separately from the spawn logic to handle both cases
player.CharacterAdded:Connect(function(character)
onCharacterAdded(player, character)
end)
end
-- Connect the functions to player events
Players.PlayerAdded:Connect(onPlayerAdded)
Players.PlayerRemoving:Connect(cleanupPlayer)
-- For players already in the game when the script runs
for _, player in ipairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
--================--
-- MAIN UPDATE LOOP
--================--
-- This function runs on every frame of the server, updating part positions and colors
RunService.Heartbeat:Connect(function(deltaTime)
-- Use tick() for a continuous time value, which is great for smooth animations like rainbows
local currentTime = tick()
for player, data in pairs(playerData) do
-- Make sure the player is still valid, has a character, and has parts to update
if not player.Character or not data.parts or #data.parts == 0 then
continue
end
local hrp = player.Character:FindFirstChild("HumanoidRootPart")
if not hrp then continue end
-- Calculate the central point for the parts
local centerPosition = hrp.Position + Vector3.new(0, CONFIG.VERTICAL_OFFSET, 0)
-- Update the mode-specific logic
if data.mode == "orbit" then
-- Increment the base angle for the orbit
data.orbitAngle = data.orbitAngle + (CONFIG.ORBIT_SPEED * deltaTime)
for i, part in ipairs(data.parts) do
-- Calculate the angle for this specific part, spreading them out evenly
local angle = data.orbitAngle + (i * (2 * math.pi / CONFIG.PART_COUNT))
-- Calculate the position offset from the center using trigonometry
local offsetX = math.cos(angle) * CONFIG.ORBIT_RADIUS
local offsetZ = math.sin(angle) * CONFIG.ORBIT_RADIUS
-- Set the part's position
part.CFrame = CFrame.new(centerPosition + Vector3.new(offsetX, 0, offsetZ))
end
elseif data.mode == "look" then
-- In this mode, all parts will face the same direction as the player
local lookDirection = hrp.CFrame.LookVector
-- CFrame.new(position, lookAtPosition)
-- This creates a CFrame at 'centerPosition' that is oriented to "look at" a point
-- in the direction of the player's look vector.
local targetCFrame = CFrame.new(centerPosition, centerPosition + lookDirection)
for _, part in ipairs(data.parts) do
part.CFrame = targetCFrame
end
end
-- Update colors for all parts regardless of mode
for i, part in ipairs(data.parts) do
-- Calculate a hue value that cycles from 0 to 1
-- We add an offset based on the part's index to create the rainbow spread
local hue = (currentTime * CONFIG.RAINBOW_SPEED + (i / CONFIG.PART_COUNT)) % 1
part.Color = Color3.fromHSV(hue, 1, 1) -- Use HSV for easy rainbow colors
end
end
end)
How It Works
Services and Configuration: We start by getting necessary services (Players, RunService) and setting up a CONFIG table. This makes it easy to change values like part count, orbit speed, and colors without digging through the code.
playerData Table: This is the heart of the script's state management. It uses player objects as keys to store their custom parts, their current mode (orbit or look), and other necessary information.
cleanupPlayer(player): This is a crucial function for preventing memory leaks. When a player leaves or respawns, it destroys their old parts and removes their data from the playerData table.
createOrbitingParts(player): This function handles the creation and setup of the 4 parts. It sets their Size, Shape, makes them Anchored and not collidable (CanCollide = false), and parents them to a folder in Workspace for tidiness.
Chat Commands (onPlayerChatted):
/spawn: When a player chats /spawn, it sets a flag needsPartsOnSpawn = true in their playerData. It then calls player:LoadCharacter(). This is an asynchronous function that respawns the player.
/change: This command checks if the player has parts. If they do, it flips the mode string in their playerData between "orbit" and "look".
Character Spawning (onCharacterAdded): This event fires every time a player's character is created (on join and on respawn). The code checks for the needsPartsOnSpawn flag. If it's true, it means the respawn was triggered by our /spawn command, so it proceeds to call createOrbitingParts. This is the correct way to handle actions that must happen after a respawn is complete.
Main Update Loop (RunService.Heartbeat):
This loop runs continuously on the server, multiple times per second.
Rainbow Color: It uses tick() (which returns the current time) to calculate a hue value that smoothly cycles. By giving each part a slight offset based on its index (i), we get a beautiful rainbow effect. is perfect for this.
Color3.fromHSV
Mode Logic: It checks the data.mode for each player.
If "orbit", it uses math.cos and math.sin with an ever-increasing angle to calculate points on a circle, updating each part's CFrame (position and rotation).
If "look", it gets the player's HumanoidRootPart.CFrame.LookVector. It then creates a new CFrame for the parts that is positioned correctly but is oriented to point in that same direction using CFrame.new(position, lookAtPosition).