Skinstashery
EN
Roblox

Scripts para Roblox Studio

30 scripts8 categorías

Scripts para Roblox Studio listos para copiar y pegar en tu propio juego. Cada uno explica qué tipo de script es, dónde va y cómo cambiarlo.

Son scripts normales para un juego que estás creando. No funcionan en juegos de otras personas ni están hechos para eso. Si empiezas hoy, prueba primero "Ladrillo asesino" y "Leaderstats (monedas)". El código está en Luau y no se traduce; lo que está en español son los títulos, los pasos y las notas.

Peligros y plataformas

Ladrillo asesinoUna parte que lastima o mata a cualquier personaje que la toque.Script
Tipo
Script (corre en el servidor)
Dónde va
Dentro de la Part
Código
-- Kill brick: put this Script inside the part that should hurt players.

local DAMAGE = 100        -- 100 kills a normal player (max health is 100)
local COOLDOWN = 1        -- seconds before the same character can be hurt again

local part = script.Parent
local recentlyHit = {}    -- humanoids that were just hurt

part.Touched:Connect(function(hit)
	local humanoid = hit.Parent and hit.Parent:FindFirstChildOfClass("Humanoid")
	if not humanoid or humanoid.Health <= 0 then
		return
	end
	if recentlyHit[humanoid] then
		return
	end

	recentlyHit[humanoid] = true
	humanoid:TakeDamage(DAMAGE)
	task.wait(COOLDOWN)
	recentlyHit[humanoid] = nil
end)

Cómo ponerlo

  1. En Studio, inserta una Part (pestaña Model, Part). Píntala de rojo si quieres.
  2. En la ventana Explorer, pasa el cursor sobre la Part, pulsa el botón de más y agrega un Script.
  3. Borra la línea print que viene por defecto y pega el código.
  4. Pulsa Play y camina hacia la parte.

Notas

  • Cambia DAMAGE a un número menor, como 20, para una parte que lastima pero no mata.
  • TakeDamage no hace nada si el jugador tiene un ForceField. Es normal: la protección al reaparecer usa uno.
  • Si no pasa nada, revisa que el Script sea hijo de la parte y no del Workspace.
  • También lastima a los NPC que tengan un Humanoid. Casi siempre es lo que quieres.
Plataforma de curaciónUna parte que devuelve salud a los jugadores que se paran encima.Script
Tipo
Script (corre en el servidor)
Dónde va
Dentro de la Part
Código
-- Heal pad: restores health to a character that touches the part.

local HEAL_AMOUNT = 25    -- health given each time
local COOLDOWN = 1        -- seconds between heals for the same character

local part = script.Parent
local recentlyHealed = {}

part.Touched:Connect(function(hit)
	local humanoid = hit.Parent and hit.Parent:FindFirstChildOfClass("Humanoid")
	if not humanoid or humanoid.Health <= 0 then
		return
	end
	if recentlyHealed[humanoid] then
		return
	end

	recentlyHealed[humanoid] = true
	humanoid.Health = math.min(humanoid.MaxHealth, humanoid.Health + HEAL_AMOUNT)
	task.wait(COOLDOWN)
	recentlyHealed[humanoid] = nil
end)

Cómo ponerlo

  1. Inserta una Part y píntala de verde para que los jugadores sepan qué es.
  2. Agrega un Script dentro de la Part.
  3. Pega el código en el Script.
  4. Juega, recibe un poco de daño y párate en la plataforma.

Notas

  • Pon HEAL_AMOUNT en 100 para curar todo de un solo toque.
  • Sube COOLDOWN (por ejemplo a 5) para que nadie se cure rápido saltando de ida y vuelta.
  • La línea con math.min evita que la salud pase de MaxHealth.
Plataforma de velocidadUna plataforma que hace correr más rápido al jugador durante unos segundos.Script
Tipo
Script (corre en el servidor)
Dónde va
Dentro de la Part
Código
-- Speed boost pad: faster walking for a short time.

local BOOST_SPEED = 40    -- the normal WalkSpeed is 16
local DURATION = 5        -- seconds the boost lasts

local part = script.Parent
local boosted = {}        -- humanoids that already have a boost running

part.Touched:Connect(function(hit)
	local humanoid = hit.Parent and hit.Parent:FindFirstChildOfClass("Humanoid")
	if not humanoid or humanoid.Health <= 0 then
		return
	end
	if boosted[humanoid] then
		return
	end

	boosted[humanoid] = true
	local originalSpeed = humanoid.WalkSpeed
	humanoid.WalkSpeed = BOOST_SPEED

	task.wait(DURATION)

	if humanoid.Parent then
		humanoid.WalkSpeed = originalSpeed
	end
	boosted[humanoid] = nil
end)

Cómo ponerlo

  1. Inserta una Part y pon su propiedad Anchored en true.
  2. Agrega un Script dentro de la Part.
  3. Pega el código.
  4. Juega y párate en la plataforma. Deberías correr más rápido durante 5 segundos.

Notas

  • Sube BOOST_SPEED para un impulso más salvaje. Con más de 100 es difícil de controlar.
  • El script recuerda la velocidad anterior y la devuelve cuando se acaba el tiempo.
  • Si también usas un script para correr, los dos pueden pelearse. Elige un solo lugar que cambie WalkSpeed.
Plataforma de salto altoUna plataforma que deja saltar mucho más alto durante unos segundos.Script
Tipo
Script (corre en el servidor)
Dónde va
Dentro de la Part
Código
-- Jump boost pad: higher jumps for a short time.

local BOOST_JUMP_POWER = 120   -- the normal JumpPower is 50
local DURATION = 8             -- seconds the boost lasts

local part = script.Parent
local boosted = {}

part.Touched:Connect(function(hit)
	local humanoid = hit.Parent and hit.Parent:FindFirstChildOfClass("Humanoid")
	if not humanoid or humanoid.Health <= 0 then
		return
	end
	if boosted[humanoid] then
		return
	end

	boosted[humanoid] = true
	local originalPower = humanoid.JumpPower
	humanoid.UseJumpPower = true        -- make sure JumpPower is used, not JumpHeight
	humanoid.JumpPower = BOOST_JUMP_POWER

	task.wait(DURATION)

	if humanoid.Parent then
		humanoid.JumpPower = originalPower
	end
	boosted[humanoid] = nil
end)

Cómo ponerlo

  1. Inserta una Part, pon Anchored en true y píntala para que resalte.
  2. Agrega un Script dentro de la Part y pega el código.
  3. Pulsa Play y párate en la plataforma.
  4. Salta. Deberías llegar mucho más alto que antes.

Notas

  • Los juegos nuevos de Roblox pueden usar JumpHeight en lugar de JumpPower. La línea UseJumpPower = true lo cambia de vuelta para que este script funcione.
  • Si tu juego usa JumpHeight a propósito, cambia el script para usar humanoid.JumpHeight y un número como 20.
  • Un salto muy alto puede lanzar a los jugadores por encima de tus muros. Prueba tu mapa después de cambiar el número.
Plataforma de teletransporteDos plataformas: te paras en una y apareces en la otra.Script
Tipo
Script (corre en el servidor)
Dónde va
Dentro de cada Part de plataforma
Código
-- Teleport pad. Use one copy of this Script in each of the two pads.
-- Pad A has TARGET_NAME = "PadB". Pad B has TARGET_NAME = "PadA".

local TARGET_NAME = "PadB"   -- name of the OTHER pad (it must be in the Workspace)
local COOLDOWN = 3           -- seconds before the same player can teleport again
local EXTRA_HEIGHT = 3       -- studs above the target pad to land

local Players = game:GetService("Players")

local pad = script.Parent
local target = workspace:WaitForChild(TARGET_NAME)

pad.Touched:Connect(function(hit)
	local character = hit.Parent
	local player = Players:GetPlayerFromCharacter(character)
	if not player then
		return
	end

	local humanoid = character:FindFirstChildOfClass("Humanoid")
	if not humanoid or humanoid.Health <= 0 then
		return
	end

	-- The cooldown is saved on the player, so both pads share it.
	-- This stops you being sent straight back when you land.
	local blockedUntil = player:GetAttribute("TeleportBlockedUntil") or 0
	if os.clock() < blockedUntil then
		return
	end
	player:SetAttribute("TeleportBlockedUntil", os.clock() + COOLDOWN)

	character:PivotTo(target.CFrame + Vector3.new(0, target.Size.Y / 2 + EXTRA_HEIGHT, 0))
end)

Cómo ponerlo

  1. Inserta dos Parts en el Workspace. Renombra una como PadA y la otra como PadB.
  2. Agrega un Script dentro de PadA. Pega el código y pon TARGET_NAME en "PadB".
  3. Agrega un Script dentro de PadB. Pega el mismo código y pon TARGET_NAME en "PadA".
  4. Juega. Camina hacia PadA y deberías aparecer en PadB.

Notas

  • Para una plataforma de un solo sentido, pon el Script solo en la plataforma de entrada.
  • Los nombres distinguen mayúsculas. PadB y padb son distintos.
  • Si la plataforma no está directamente en el Workspace (por ejemplo, dentro de un Model), cambia la ruta de workspace:WaitForChild.
  • Sube EXTRA_HEIGHT si los jugadores se quedan atorados en la plataforma de destino.
Lava que subeLava que sube despacio, mata al tocarla, baja de nuevo y vuelve a empezar.Script
Tipo
Script (corre en el servidor)
Dónde va
Dentro de la Part de lava
Código
-- Rising lava: the part climbs, kills on touch, then resets and repeats.

local START_DELAY = 10       -- seconds before the lava starts to rise
local RISE_HEIGHT = 60       -- studs to rise
local RISE_TIME = 90         -- seconds to rise that far
local PAUSE_AT_TOP = 5       -- seconds to wait at the top
local RESET_DELAY = 5        -- seconds to wait after dropping back down

local TweenService = game:GetService("TweenService")

local lava = script.Parent
lava.Anchored = true

local startPosition = lava.Position
local endPosition = startPosition + Vector3.new(0, RISE_HEIGHT, 0)

-- Kill anything with a Humanoid that touches the lava.
lava.Touched:Connect(function(hit)
	local humanoid = hit.Parent and hit.Parent:FindFirstChildOfClass("Humanoid")
	if humanoid and humanoid.Health > 0 then
		humanoid.Health = 0
	end
end)

local riseTween = TweenService:Create(
	lava,
	TweenInfo.new(RISE_TIME, Enum.EasingStyle.Linear),
	{ Position = endPosition }
)

while true do
	lava.Position = startPosition
	task.wait(START_DELAY)

	riseTween:Play()
	riseTween.Completed:Wait()

	task.wait(PAUSE_AT_TOP)
	lava.Position = startPosition
	task.wait(RESET_DELAY)
end

Cómo ponerlo

  1. Inserta una Part grande y plana debajo de tu mapa. Píntala de naranja y pon el Material en Neon.
  2. Acomoda tu mapa para que la lava pueda subir más allá de él.
  3. Agrega un Script dentro de la Part de lava y pega el código.
  4. Juega. Después de 10 segundos la lava empieza a subir.

Notas

  • Un RISE_TIME corto lo hace más difícil. 90 segundos para subir 60 studs es algo tranquilo.
  • Haz la lava lo bastante grande para que nadie pueda rodear el borde.
  • Los jugadores que reaparezcan aparecerán en tu SpawnLocation. Déjalo por encima de la altura inicial de la lava.

Puertas e interacción

Puerta con clicUna puerta que se abre cuando el jugador hace clic y se cierra sola.Script
Tipo
Script (corre en el servidor)
Dónde va
Dentro de la Part de la puerta
Código
-- Click door: click the part to open it. It closes after a few seconds.

local OPEN_TIME = 3          -- seconds the door stays open
local OPEN_TRANSPARENCY = 0.7
local MAX_CLICK_DISTANCE = 12

local door = script.Parent

local detector = door:FindFirstChildOfClass("ClickDetector")
if not detector then
	detector = Instance.new("ClickDetector")
	detector.Parent = door
end
detector.MaxActivationDistance = MAX_CLICK_DISTANCE

local isOpen = false

detector.MouseClick:Connect(function(player)
	if isOpen then
		return
	end
	isOpen = true

	door.CanCollide = false
	door.Transparency = OPEN_TRANSPARENCY

	task.wait(OPEN_TIME)

	door.CanCollide = true
	door.Transparency = 0
	isOpen = false
end)

Cómo ponerlo

  1. Inserta una Part y dale forma de puerta. Pon Anchored en true.
  2. Agrega un Script dentro de la Part de la puerta.
  3. Pega el código. El script agrega el ClickDetector por ti.
  4. Juega, acércate a la puerta y haz clic.

Notas

  • Cambia OPEN_TIME para que la puerta se quede abierta más tiempo.
  • Si un jugador está en el marco cuando se cierra, puede quedar atorado. Deja OPEN_TIME lo bastante largo para cruzar.
  • El cursor cambia a una mano cuando apuntas a la puerta. Puedes cambiarlo con detector.CursorIcon.
Puerta con tecla de acciónUna puerta que se abre cuando el jugador se acerca y pulsa la tecla que aparece.Script
Tipo
Script (corre en el servidor)
Dónde va
Dentro de la Part de la puerta
Código
-- Proximity prompt door: press E near the door to open or close it.

local ACTION_TEXT_OPEN = "Open"
local ACTION_TEXT_CLOSE = "Close"
local OBJECT_TEXT = "Door"
local HOLD_DURATION = 0       -- seconds to hold the key; 0 means a tap
local MAX_DISTANCE = 10

local door = script.Parent

local prompt = door:FindFirstChildOfClass("ProximityPrompt")
if not prompt then
	prompt = Instance.new("ProximityPrompt")
	prompt.Parent = door
end
prompt.ObjectText = OBJECT_TEXT
prompt.ActionText = ACTION_TEXT_OPEN
prompt.HoldDuration = HOLD_DURATION
prompt.MaxActivationDistance = MAX_DISTANCE

local isOpen = false

prompt.Triggered:Connect(function(player)
	isOpen = not isOpen

	door.CanCollide = not isOpen
	door.Transparency = if isOpen then 0.7 else 0
	prompt.ActionText = if isOpen then ACTION_TEXT_CLOSE else ACTION_TEXT_OPEN
end)

Cómo ponerlo

  1. Inserta una Part para la puerta y pon Anchored en true.
  2. Agrega un Script dentro de la Part y pega el código.
  3. Juega y acércate a la puerta. Aparece un aviso pequeño con una tecla.
  4. Pulsa la tecla (E en el teclado) para abrir la puerta. Púlsala otra vez para cerrarla.

Notas

  • Pon HOLD_DURATION en 1 si quieres que el jugador mantenga pulsada la tecla.
  • Estos avisos también funcionan en celulares y con control, por eso son mejores que el clic en juegos nuevos.
  • Para una puerta que se cierre sola, agrega un task.wait y vuelve a poner la puerta en su lugar después de que se active el aviso.
Puerta solo para un equipoUna puerta que solo se abre para los jugadores de un equipo.Script
Tipo
Script (corre en el servidor)
Dónde va
Dentro de la Part de la puerta
Código
-- Team-only door: opens briefly when a member of the right team touches it.

local TEAM_NAME = "Red"     -- the exact name of the team in the Teams service
local OPEN_TIME = 2          -- seconds the door stays open

local Players = game:GetService("Players")

local door = script.Parent
local isOpen = false

door.Touched:Connect(function(hit)
	if isOpen then
		return
	end

	local player = Players:GetPlayerFromCharacter(hit.Parent)
	if not player or not player.Team then
		return
	end
	if player.Team.Name ~= TEAM_NAME then
		return
	end

	isOpen = true
	door.CanCollide = false
	door.Transparency = 0.7

	task.wait(OPEN_TIME)

	door.CanCollide = true
	door.Transparency = 0
	isOpen = false
end)

Cómo ponerlo

  1. En el Explorer, busca Teams. Pulsa el botón de más y agrega un Team. Llámalo Red y elige un TeamColor.
  2. Agrega un segundo Team (por ejemplo Blue). Agrega un SpawnLocation para cada equipo y pon su TeamColor y Neutral = false.
  3. Inserta una Part para la puerta, pon Anchored en true y agrégale un Script con el código.
  4. Juega. Los jugadores de Red pueden pasar. Los de Blue no.

Notas

  • TEAM_NAME tiene que coincidir exactamente con el nombre del Team, con las mismas mayúsculas.
  • Los jugadores sin equipo (neutrales) nunca pasan.
  • Mientras está abierta, la puerta deja pasar a todos los que estén cerca. Para una entrada estricta de una sola persona, usa grupos de colisión.
Dar una herramienta al tocarUna parte que da al jugador una herramienta de ServerStorage cuando la toca.Script
Tipo
Script (corre en el servidor)
Dónde va
Dentro de la Part
Código
-- Give tool on touch: copies a Tool from ServerStorage into the player's Backpack.

local TOOL_NAME = "Sword"    -- the name of a Tool inside ServerStorage
local COOLDOWN = 2           -- seconds before the same player can be checked again

local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")

local part = script.Parent
local tool = ServerStorage:WaitForChild(TOOL_NAME)
local busy = {}

local function playerHasTool(player)
	local backpack = player:FindFirstChildOfClass("Backpack")
	if backpack and backpack:FindFirstChild(TOOL_NAME) then
		return true
	end
	local character = player.Character
	if character and character:FindFirstChild(TOOL_NAME) then
		return true
	end
	return false
end

part.Touched:Connect(function(hit)
	local player = Players:GetPlayerFromCharacter(hit.Parent)
	if not player or busy[player] then
		return
	end

	busy[player] = true

	if not playerHasTool(player) then
		local backpack = player:FindFirstChildOfClass("Backpack")
		if backpack then
			tool:Clone().Parent = backpack
		end
	end

	task.wait(COOLDOWN)
	busy[player] = nil
end)

Cómo ponerlo

  1. Crea o inserta un Tool (Explorer, botón de más, Tool). Dale una Part llamada Handle.
  2. Arrastra el Tool a ServerStorage y renómbralo Sword (o el nombre que quieras).
  3. Inserta una Part, agrégale un Script y pega el código. Pon TOOL_NAME con el nombre de tu herramienta.
  4. Juega y toca la parte. La herramienta aparece en tu barra de objetos.

Notas

  • La herramienta se pierde cuando el jugador muere, porque el Backpack se reinicia. Usa una copia en StarterPack si quieres que se quede.
  • El script revisa si el jugador ya tiene la herramienta, para que nadie junte 50 espadas.
  • La herramienta debe ser un objeto Tool con un Handle, o no se podrá sostener.

Movimiento

Correr con ShiftMantén pulsada la tecla Shift izquierda para correr más rápido. Suéltala para caminar.LocalScript
Tipo
LocalScript (corre en el dispositivo del jugador)
Dónde va
StarterPlayer > StarterPlayerScripts
Código
-- Sprint: hold the key to run faster. This is a LocalScript (it runs on the player's own device).

local WALK_SPEED = 16
local SPRINT_SPEED = 28
local SPRINT_KEY = Enum.KeyCode.LeftShift

local Players = game:GetService("Players")
local UserInputService = game:GetService("UserInputService")

local player = Players.LocalPlayer

local function getHumanoid()
	local character = player.Character
	return character and character:FindFirstChildOfClass("Humanoid")
end

UserInputService.InputBegan:Connect(function(input, gameProcessed)
	if gameProcessed then
		return -- the player is typing in chat or using a menu
	end
	if input.KeyCode == SPRINT_KEY then
		local humanoid = getHumanoid()
		if humanoid then
			humanoid.WalkSpeed = SPRINT_SPEED
		end
	end
end)

UserInputService.InputEnded:Connect(function(input)
	if input.KeyCode == SPRINT_KEY then
		local humanoid = getHumanoid()
		if humanoid then
			humanoid.WalkSpeed = WALK_SPEED
		end
	end
end)

Cómo ponerlo

  1. En el Explorer, abre StarterPlayer y luego StarterPlayerScripts.
  2. Pulsa el botón de más junto a StarterPlayerScripts y agrega un LocalScript.
  3. Pega el código en el LocalScript.
  4. Juega y mantén pulsada la tecla Shift izquierda mientras caminas.

Notas

  • Solo funciona con teclado. Quienes juegan en celular necesitan un botón en pantalla, que es otro script.
  • La velocidad que se cambia en el dispositivo del jugador la puede modificar alguien que haga trampa. Si la velocidad importa en tu juego, pasa la revisión al servidor.
  • Cambia SPRINT_KEY a Enum.KeyCode.LeftControl o a cualquier otra tecla.
Doble saltoPulsa saltar otra vez en el aire para dar un segundo salto.LocalScript
Tipo
LocalScript (corre en el dispositivo del jugador)
Dónde va
StarterPlayer > StarterPlayerScripts
Código
-- Double jump: press Jump again while in the air.

local MAX_JUMPS = 2          -- 2 = one extra jump in the air. 3 = triple jump.

local Players = game:GetService("Players")
local UserInputService = game:GetService("UserInputService")

local player = Players.LocalPlayer

local humanoid = nil
local airJumpsUsed = 0

local function onCharacterAdded(character)
	humanoid = character:WaitForChild("Humanoid")
	airJumpsUsed = 0

	humanoid.StateChanged:Connect(function(_, newState)
		-- Touching the ground gives the extra jumps back.
		if newState == Enum.HumanoidStateType.Landed
			or newState == Enum.HumanoidStateType.Running then
			airJumpsUsed = 0
		end
	end)
end

player.CharacterAdded:Connect(onCharacterAdded)
if player.Character then
	onCharacterAdded(player.Character)
end

UserInputService.JumpRequest:Connect(function()
	if not humanoid or humanoid.Health <= 0 then
		return
	end

	local state = humanoid:GetState()
	if state == Enum.HumanoidStateType.Freefall and airJumpsUsed < MAX_JUMPS - 1 then
		airJumpsUsed += 1
		humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
	end
end)

Cómo ponerlo

  1. En el Explorer, abre StarterPlayer y luego StarterPlayerScripts.
  2. Agrega ahí un LocalScript.
  3. Pega el código.
  4. Juega, salta y pulsa Espacio otra vez en el aire.

Notas

  • Pon MAX_JUMPS en 3 para un triple salto.
  • El script devuelve los saltos cuando aterrizas. Caer de una orilla cuenta como estar en el aire, así que aún puedes usar el salto extra.
  • Como corre en el dispositivo del jugador, sirve para divertirse. No está a prueba de trampas.

Mundo y efectos

Plataforma que se mueveUna plataforma que va y viene entre dos puntos con TweenService.Script
Tipo
Script (corre en el servidor)
Dónde va
Dentro de la Part de la plataforma
Código
-- Moving platform: slides from its start position to START + OFFSET and back.

local OFFSET = Vector3.new(0, 0, 40)   -- how far to move (x, y, z in studs)
local TRAVEL_TIME = 4                  -- seconds for one trip
local WAIT_AT_ENDS = 1                 -- seconds to pause at each end

local TweenService = game:GetService("TweenService")

local platform = script.Parent
platform.Anchored = true

local startPosition = platform.Position
local endPosition = startPosition + OFFSET

local info = TweenInfo.new(TRAVEL_TIME, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut)
local forward = TweenService:Create(platform, info, { Position = endPosition })
local backward = TweenService:Create(platform, info, { Position = startPosition })

while true do
	forward:Play()
	forward.Completed:Wait()
	task.wait(WAIT_AT_ENDS)

	backward:Play()
	backward.Completed:Wait()
	task.wait(WAIT_AT_ENDS)
end

Cómo ponerlo

  1. Inserta una Part plana para la plataforma.
  2. Agrega un Script dentro y pega el código.
  3. Pon la plataforma donde quieres que empiece. El código lee su posición cuando arranca el juego.
  4. Juega y súbete. Los jugadores viajan encima de ella.

Notas

  • Cambia OFFSET a Vector3.new(0, 30, 0) para hacer un elevador.
  • El easing Sine la frena en cada extremo. Usa Enum.EasingStyle.Linear para una velocidad constante.
  • Deja libre el camino de muros, o la plataforma los atravesará sin detenerse.
Parte que giraUna parte que da vueltas sin parar, como las aspas de un ventilador o una barra giratoria.Script
Tipo
Script (corre en el servidor)
Dónde va
Dentro de la Part
Código
-- Spinning part: turns the part around its own centre.

local DEGREES_PER_SECOND = 90
local AXIS = Vector3.new(0, 1, 0)   -- (0,1,0) turns it like a record player

local RunService = game:GetService("RunService")

local part = script.Parent
part.Anchored = true

local radiansPerSecond = math.rad(DEGREES_PER_SECOND)

RunService.Heartbeat:Connect(function(deltaTime)
	part.CFrame = part.CFrame * CFrame.fromAxisAngle(AXIS, radiansPerSecond * deltaTime)
end)

Cómo ponerlo

  1. Inserta una Part. Una larga y delgada sirve como barra giratoria.
  2. Agrega un Script dentro de la Part y pega el código.
  3. Juega. La parte gira sin detenerse.

Notas

  • Un DEGREES_PER_SECOND negativo la hace girar al otro lado.
  • Usa AXIS = Vector3.new(1, 0, 0) para que ruede como una rueda.
  • Usar deltaTime mantiene la misma velocidad en computadoras rápidas y lentas.
  • Combínala con el script del ladrillo asesino para hacer un obstáculo giratorio.
Plataforma que desapareceUna plataforma que se desvanece cuando alguien la pisa y luego regresa.Script
Tipo
Script (corre en el servidor)
Dónde va
Dentro de la Part
Código
-- Disappearing platform: touched -> short delay -> gone -> comes back.

local DELAY_BEFORE_FALL = 1     -- seconds after the touch before it vanishes
local TIME_GONE = 3             -- seconds it stays invisible
local FADE_TIME = 0.4           -- seconds the fade takes

local Players = game:GetService("Players")
local TweenService = game:GetService("TweenService")

local platform = script.Parent
local active = false

platform.Touched:Connect(function(hit)
	if active then
		return
	end
	if not Players:GetPlayerFromCharacter(hit.Parent) then
		return
	end

	active = true

	task.wait(DELAY_BEFORE_FALL)

	local fadeOut = TweenService:Create(platform, TweenInfo.new(FADE_TIME), { Transparency = 1 })
	fadeOut:Play()
	fadeOut.Completed:Wait()
	platform.CanCollide = false

	task.wait(TIME_GONE)

	platform.CanCollide = true
	local fadeIn = TweenService:Create(platform, TweenInfo.new(FADE_TIME), { Transparency = 0 })
	fadeIn:Play()
	fadeIn.Completed:Wait()

	active = false
end)

Cómo ponerlo

  1. Inserta una Part y pon Anchored en true.
  2. Agrega un Script dentro de la Part y pega el código.
  3. Copia y pega la parte completa para hacer una fila de plataformas. Cada copia conserva su propio script.
  4. Juega y camina sobre ellas.

Notas

  • Baja DELAY_BEFORE_FALL para un obby más difícil.
  • Al volver, la plataforma queda en Transparency 0. Si tu parte ya era transparente, cambia el 0 por su valor anterior.
  • Solo la activan los jugadores. Las partes sueltas y los NPC no.
Ciclo de día y nocheMueve el sol y la luna para que el juego pase por un día completo en el tiempo que elijas.Script
Tipo
Script (corre en el servidor)
Dónde va
ServerScriptService
Código
-- Day and night cycle: changes Lighting.ClockTime from 0 to 24 over and over.

local DAY_LENGTH_SECONDS = 600   -- real seconds for one full 24 hour game day
local START_HOUR = 8             -- the hour the game starts at (0 to 24)
local STEP_SECONDS = 0.25        -- how often the clock updates

local Lighting = game:GetService("Lighting")

Lighting.ClockTime = START_HOUR

local hoursPerStep = 24 / DAY_LENGTH_SECONDS * STEP_SECONDS

while true do
	Lighting.ClockTime = (Lighting.ClockTime + hoursPerStep) % 24
	task.wait(STEP_SECONDS)
end

Cómo ponerlo

  1. En el Explorer, busca ServerScriptService.
  2. Pulsa el botón de más junto a él y agrega un Script.
  3. Pega el código.
  4. Juega y mira cómo cambia el cielo. Prueba DAY_LENGTH_SECONDS = 60 para verlo rápido.

Notas

  • ClockTime 12 es mediodía y 0 es medianoche.
  • Lighting.Brightness y Ambient no cambian solos. Ponlos en valores que también se vean bien de noche.
  • Para una noche más corta, salta horas cuando ClockTime esté entre 20 y 6.
Cambio de color aleatorioCambia cada pocos segundos el color de todas las partes de una carpeta a uno al azar.Script
Tipo
Script (corre en el servidor)
Dónde va
ServerScriptService
Código
-- Random colour changer: every part in the folder gets a new colour on a timer.

local FOLDER_NAME = "ColorParts"   -- a Folder in the Workspace that holds your parts
local INTERVAL = 3                 -- seconds between changes
local FADE_TIME = 1                -- seconds each colour takes to blend

local TweenService = game:GetService("TweenService")

local folder = workspace:WaitForChild(FOLDER_NAME)

while true do
	for _, child in folder:GetDescendants() do
		if child:IsA("BasePart") then
			local newColor = Color3.fromHSV(math.random(), 0.7, 1)
			TweenService:Create(child, TweenInfo.new(FADE_TIME), { Color = newColor }):Play()
		end
	end
	task.wait(INTERVAL)
end

Cómo ponerlo

  1. En el Explorer, haz clic derecho en Workspace, elige Insert Object y luego Folder. Llámala ColorParts.
  2. Arrastra a esa carpeta las partes que quieras cambiar.
  3. Agrega un Script en ServerScriptService y pega el código.
  4. Juega y míralas cambiar.

Notas

  • Sube el segundo número de Color3.fromHSV (saturación, de 0 a 1) para colores más fuertes.
  • Para usar solo unos cuantos colores fijos, haz una tabla de valores Color3 y elige uno con math.random(#colours).
  • Pon FADE_TIME en 0 para un cambio instantáneo.
NPC que sigue al jugadorUn NPC que busca al jugador más cercano y camina hacia él esquivando obstáculos.Script
Tipo
Script (corre en el servidor)
Dónde va
Dentro del Model del NPC
Código
-- NPC that follows the nearest player using PathfindingService.
-- The model needs a Humanoid and a HumanoidRootPart.

local DETECT_RANGE = 80       -- studs; ignores players further away
local STOP_DISTANCE = 5       -- studs; stops when this close
local UPDATE_TIME = 0.4       -- seconds between path updates

local Players = game:GetService("Players")
local PathfindingService = game:GetService("PathfindingService")

local npc = script.Parent
local humanoid = npc:WaitForChild("Humanoid")
local root = npc:WaitForChild("HumanoidRootPart")

-- Let the server move the NPC smoothly (no stutter from a nearby player owning it).
pcall(function()
	root:SetNetworkOwner(nil)
end)

local function findNearestTarget()
	local nearestRoot = nil
	local nearestDistance = DETECT_RANGE

	for _, player in Players:GetPlayers() do
		local character = player.Character
		local targetHumanoid = character and character:FindFirstChildOfClass("Humanoid")
		local targetRoot = character and character:FindFirstChild("HumanoidRootPart")
		if targetHumanoid and targetRoot and targetHumanoid.Health > 0 then
			local distance = (targetRoot.Position - root.Position).Magnitude
			if distance < nearestDistance then
				nearestDistance = distance
				nearestRoot = targetRoot
			end
		end
	end

	return nearestRoot, nearestDistance
end

while humanoid.Health > 0 do
	local targetRoot, distance = findNearestTarget()

	if targetRoot and distance > STOP_DISTANCE then
		local path = PathfindingService:CreatePath({
			AgentRadius = 2,
			AgentHeight = 5,
			AgentCanJump = true,
		})

		local ok = pcall(function()
			path:ComputeAsync(root.Position, targetRoot.Position)
		end)

		if ok and path.Status == Enum.PathStatus.Success then
			local waypoints = path:GetWaypoints()
			local nextWaypoint = waypoints[2] -- waypoint 1 is where the NPC already stands
			if nextWaypoint then
				if nextWaypoint.Action == Enum.PathWaypointAction.Jump then
					humanoid.Jump = true
				end
				humanoid:MoveTo(nextWaypoint.Position)
			end
		else
			-- No path found: walk straight at the player.
			humanoid:MoveTo(targetRoot.Position)
		end
	end

	task.wait(UPDATE_TIME)
end

Cómo ponerlo

  1. Consigue un modelo de NPC. En la pestaña Avatar, Rig Builder crea uno con un clic. Asegúrate de que no esté anclado.
  2. Agrega un Script dentro del modelo del NPC (no dentro de una de sus partes).
  3. Pega el código.
  4. Pon algunos muros y huecos en el mapa y pulsa Play. El NPC los rodea para llegar a ti.

Notas

  • Esta es la versión sencilla: recalcula el camino seguido y da un paso cada vez. Sirve para uno o pocos NPC.
  • Haz que AgentRadius y AgentHeight coincidan con el tamaño de tu NPC. Los NPC grandes necesitan números más grandes.
  • Para que lastime a los jugadores, agrega un script de daño con Touched como el del ladrillo asesino, o usa TakeDamage cuando la distancia sea pequeña.
  • Si el NPC no se mueve, revisa que ninguna de sus partes esté Anchored.

Datos del jugador y dinero

Leaderstats (monedas)Agrega un número de Coins a la lista de jugadores, arriba a la derecha de la pantalla.Script
Tipo
Script (corre en el servidor)
Dónde va
ServerScriptService
Código
-- Leaderstats: creates the player list board with a Coins value.

local STARTING_COINS = 0

local Players = game:GetService("Players")

local function onPlayerAdded(player)
	-- The folder MUST be called "leaderstats" for Roblox to show it.
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local coins = Instance.new("IntValue")
	coins.Name = "Coins"
	coins.Value = STARTING_COINS
	coins.Parent = leaderstats
end

Players.PlayerAdded:Connect(onPlayerAdded)

-- Also handle players who joined before this script finished loading.
for _, player in Players:GetPlayers() do
	task.spawn(onPlayerAdded, player)
end

Cómo ponerlo

  1. Abre ServerScriptService en el Explorer.
  2. Agrega un Script y pega el código.
  3. Juega. Arriba a la derecha aparece una caja con tu nombre y tus Coins.
  4. Para verlo cambiar mientras pruebas, selecciona Coins en el Explorer (en Players > tu nombre > leaderstats) y edita el valor.

Notas

  • Para agregar más datos, copia el bloque del IntValue y cambia el nombre, por ejemplo Gems.
  • Usa un StringValue para texto y un NumberValue para decimales.
  • Cambia leaderstats solo desde un Script. Un cambio desde un LocalScript solo se ve en esa pantalla y no afecta al juego real.
  • Combínalo con el script de guardar datos para conservar las monedas entre visitas.
Moneda para recogerUna moneda que suma a las leaderstats del jugador cuando la toca y vuelve a aparecer después de un rato.Script
Tipo
Script (corre en el servidor)
Dónde va
Dentro de la Part de la moneda
Código
-- Coin pickup: gives coins and respawns after a delay.
-- Needs the Leaderstats (coins) script so player.leaderstats.Coins exists.

local COIN_VALUE = 1
local RESPAWN_TIME = 10       -- seconds before the coin comes back. Use 0 to remove it for good.

local Players = game:GetService("Players")

local coin = script.Parent
local collected = false

coin.Touched:Connect(function(hit)
	if collected then
		return
	end

	local player = Players:GetPlayerFromCharacter(hit.Parent)
	if not player then
		return
	end

	local leaderstats = player:FindFirstChild("leaderstats")
	local coins = leaderstats and leaderstats:FindFirstChild("Coins")
	if not coins then
		return
	end

	collected = true
	coins.Value += COIN_VALUE

	-- Hide the coin.
	coin.Transparency = 1
	coin.CanTouch = false

	if RESPAWN_TIME <= 0 then
		coin:Destroy()
		return
	end

	task.wait(RESPAWN_TIME)

	coin.Transparency = 0
	coin.CanTouch = true
	collected = false
end)

Cómo ponerlo

  1. Asegúrate de que el script Leaderstats (monedas) ya esté en ServerScriptService.
  2. Inserta una Part, hazla un cilindro amarillo o un disco plano y pon Anchored en true. Desactiva CanCollide.
  3. Agrega un Script dentro de la Part y pega el código.
  4. Copia y pega la moneda por el mapa. Juega y recógelas.

Notas

  • La moneda la da el servidor, así que los jugadores no pueden inventar sus propias monedas.
  • Cambia COIN_VALUE a 5 o 10 para una moneda más valiosa.
  • Si las monedas no cuentan, revisa que el dato se llame exactamente Coins y la carpeta exactamente leaderstats.
Guardar datos con DataStoreCarga y guarda las Coins de cada jugador entre visitas, con reintentos y manejo seguro de errores.Script
Tipo
Script (corre en el servidor)
Dónde va
ServerScriptService
Código
-- Save data: loads Coins when a player joins and saves when they leave.
-- This script makes the leaderstats itself. Do not also use the Leaderstats (coins) script.

local STORE_NAME = "PlayerData_v1"   -- change the name to start with a fresh, empty store
local DEFAULT_COINS = 0
local AUTOSAVE_SECONDS = 120
local MAX_TRIES = 3

local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")

local store = DataStoreService:GetDataStore(STORE_NAME)
local loaded = {}   -- players whose data loaded OK. We only save these.

-- Runs fn up to MAX_TRIES times. Returns true and the result, or false.
local function tryCall(fn)
	for attempt = 1, MAX_TRIES do
		local ok, result = pcall(fn)
		if ok then
			return true, result
		end
		warn("DataStore call failed (try " .. attempt .. "): " .. tostring(result))
		task.wait(2)
	end
	return false, nil
end

local function keyFor(player)
	return "Player_" .. player.UserId
end

local function savePlayer(player)
	if not loaded[player] then
		return -- the load failed, so saving would wipe real data with defaults
	end

	local leaderstats = player:FindFirstChild("leaderstats")
	local coins = leaderstats and leaderstats:FindFirstChild("Coins")
	if not coins then
		return
	end

	local data = { Coins = coins.Value }
	local ok = tryCall(function()
		store:SetAsync(keyFor(player), data)
	end)
	if not ok then
		warn("Could not save data for " .. player.Name)
	end
end

local function onPlayerAdded(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local coins = Instance.new("IntValue")
	coins.Name = "Coins"
	coins.Value = DEFAULT_COINS
	coins.Parent = leaderstats

	local ok, data = tryCall(function()
		return store:GetAsync(keyFor(player))
	end)

	if not ok then
		warn("Could not load data for " .. player.Name .. ". Their progress will not be saved this visit.")
		return
	end

	if type(data) == "table" and type(data.Coins) == "number" then
		coins.Value = data.Coins
	end
	loaded[player] = true
end

local function onPlayerRemoving(player)
	savePlayer(player)
	loaded[player] = nil
end

Players.PlayerAdded:Connect(onPlayerAdded)
Players.PlayerRemoving:Connect(onPlayerRemoving)

for _, player in Players:GetPlayers() do
	task.spawn(onPlayerAdded, player)
end

-- Save everyone when the server shuts down.
game:BindToClose(function()
	for _, player in Players:GetPlayers() do
		task.spawn(savePlayer, player)
	end
	task.wait(3)
end)

-- Save everyone every couple of minutes in case of a crash.
task.spawn(function()
	while true do
		task.wait(AUTOSAVE_SECONDS)
		for _, player in Players:GetPlayers() do
			task.spawn(savePlayer, player)
		end
	end
end)

Cómo ponerlo

  1. En Studio, abre Home > Game Settings > Security y activa "Enable Studio Access to API Services". Sin esto, guardar falla en Studio.
  2. Publica tu juego (File > Publish to Roblox). Los DataStores necesitan un juego publicado.
  3. Agrega un Script en ServerScriptService y pega el código. Quita cualquier otro Script que cree leaderstats.
  4. Juega, cambia el valor de tus Coins en el Explorer, detén la prueba y vuelve a jugar. El número debería seguir ahí.

Notas

  • Las llamadas a DataStore pueden fallar, por eso cada una va dentro de un pcall. Si falla la carga, esa visita no guarda nada. Así los jugadores no pierden sus monedas.
  • Para guardar más valores, agrégalos a la tabla data y léelos de vuelta en onPlayerAdded.
  • Si cambias STORE_NAME se crea un almacén nuevo y los jugadores empiezan de cero. Hazlo solo mientras pruebas.
  • No guardes más de una vez cada pocos segundos por jugador. Roblox limita cuántas peticiones puedes hacer.
Botón de tienda (RemoteEvent)Un botón de compra donde el servidor revisa el precio y las monedas, para que nadie pueda hacer trampa.Script
Tipo
Script (corre en el servidor)
Dónde va
ServerScriptService
Script del servidor · Script · ServerScriptService
-- Shop (server side). The server decides if a purchase is allowed.
-- The client only says WHICH item it wants. It never says the price.
-- Needs the Leaderstats (coins) or Save data script so player.leaderstats.Coins exists.

local ITEMS = {
	-- [item name] = { price = coins, tool = name of a Tool in ServerStorage }
	Sword = { price = 50, tool = "Sword" },
	Torch = { price = 20, tool = "Torch" },
}
local BUY_COOLDOWN = 0.5   -- seconds between purchases for one player

local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")

-- Make the RemoteEvent if it is not there yet.
local buyEvent = ReplicatedStorage:FindFirstChild("BuyItem")
if not buyEvent then
	buyEvent = Instance.new("RemoteEvent")
	buyEvent.Name = "BuyItem"
	buyEvent.Parent = ReplicatedStorage
end

local lastBuy = {}

buyEvent.OnServerEvent:Connect(function(player, itemName)
	-- 1. Check what the client sent. Never trust it.
	if type(itemName) ~= "string" then
		return
	end
	local item = ITEMS[itemName]
	if not item then
		return
	end

	-- 2. Slow down spam.
	local now = os.clock()
	if lastBuy[player] and now - lastBuy[player] < BUY_COOLDOWN then
		return
	end
	lastBuy[player] = now

	-- 3. Check the player can pay.
	local leaderstats = player:FindFirstChild("leaderstats")
	local coins = leaderstats and leaderstats:FindFirstChild("Coins")
	if not coins or coins.Value < item.price then
		return
	end

	-- 4. Check the tool exists and the player has a Backpack.
	local template = ServerStorage:FindFirstChild(item.tool)
	local backpack = player:FindFirstChildOfClass("Backpack")
	if not template or not backpack then
		return
	end

	-- 5. Take the coins, give the item.
	coins.Value -= item.price
	template:Clone().Parent = backpack
end)

Players.PlayerRemoving:Connect(function(player)
	lastBuy[player] = nil
end)
Script del botón · LocalScript · Dentro del TextButton (StarterGui > ScreenGui > TextButton)
-- Shop button (client side). Sends the item name to the server when clicked.

local ITEM_NAME = "Sword"   -- must match a name in the ITEMS table on the server

local ReplicatedStorage = game:GetService("ReplicatedStorage")

local button = script.Parent
local buyEvent = ReplicatedStorage:WaitForChild("BuyItem")

button.Activated:Connect(function()
	buyEvent:FireServer(ITEM_NAME)
end)

Cómo ponerlo

  1. Pon dos Tools llamados Sword y Torch en ServerStorage (o cambia los nombres en la tabla ITEMS).
  2. Agrega el Script del servidor, el de arriba, a ServerScriptService. Asegúrate de tener un script que cree leaderstats con Coins.
  3. En StarterGui, agrega un ScreenGui y dentro de él un TextButton. Pon su Text en "Comprar espada".
  4. Agrega el LocalScript (el segundo bloque de código) dentro del TextButton. Pulsa Play y date monedas en el Explorer para probar.

Notas

  • El precio vive solo en el servidor. Alguien que haga trampa puede disparar el evento, pero solo logra pedir un objeto. El servidor igual cobra las monedas.
  • Para un segundo botón, copia el TextButton y cambia ITEM_NAME en su LocalScript.
  • Todo lo que dé monedas, objetos o niveles debe revisarse así en el servidor.
  • Este script no le responde al jugador. Para mostrar "No tienes suficientes monedas", agrega un segundo RemoteEvent que el servidor dispare de vuelta.
Revisar un game passRevisa si el jugador tiene un game pass y le da una ventaja, incluso justo después de comprarlo.Script
Tipo
Script (corre en el servidor)
Dónde va
ServerScriptService
Código
-- Game pass check: gives a faster walk speed to players who own the pass.

local GAME_PASS_ID = 0        -- replace with your game pass ID
local PERK_WALK_SPEED = 24    -- what owners get (the normal speed is 16)

local Players = game:GetService("Players")
local MarketplaceService = game:GetService("MarketplaceService")

local function ownsPass(player)
	if GAME_PASS_ID == 0 then
		return false
	end
	local ok, result = pcall(function()
		return MarketplaceService:UserOwnsGamePassAsync(player.UserId, GAME_PASS_ID)
	end)
	if not ok then
		warn("Could not check the game pass for " .. player.Name .. ": " .. tostring(result))
		return false
	end
	return result
end

local function applyPerk(player)
	local character = player.Character
	local humanoid = character and character:FindFirstChildOfClass("Humanoid")
	if humanoid then
		humanoid.WalkSpeed = PERK_WALK_SPEED
	end
end

local function onPlayerAdded(player)
	local owns = ownsPass(player)
	player:SetAttribute("HasPass", owns)

	-- Give the perk every time the character spawns.
	player.CharacterAdded:Connect(function()
		if player:GetAttribute("HasPass") then
			applyPerk(player)
		end
	end)

	if owns then
		applyPerk(player)
	end
end

Players.PlayerAdded:Connect(onPlayerAdded)
for _, player in Players:GetPlayers() do
	task.spawn(onPlayerAdded, player)
end

-- If the player buys the pass while playing, give the perk straight away.
MarketplaceService.PromptGamePassPurchaseFinished:Connect(function(player, passId, wasPurchased)
	if wasPurchased and passId == GAME_PASS_ID then
		player:SetAttribute("HasPass", true)
		applyPerk(player)
	end
end)

Cómo ponerlo

  1. En el Creator Dashboard de Roblox, abre tu juego, entra a Monetization > Passes y crea un pase. Copia su número de ID.
  2. Pega el ID donde dice 0 en GAME_PASS_ID.
  3. Agrega el Script a ServerScriptService.
  4. Para que puedan comprarlo, llama a MarketplaceService:PromptGamePassPurchase(player, GAME_PASS_ID) desde un botón o un script de ProximityPrompt. Al probar en Studio, quizá la cuenta que hizo el juego deba comprarlo para ver la ventaja.

Notas

  • Mientras GAME_PASS_ID sea 0, el script no hace nada. No le dará la ventaja a todos por error.
  • UserOwnsGamePassAsync habla con los servidores de Roblox y puede fallar, por eso va dentro de un pcall.
  • Cambia applyPerk para dar una herramienta, una etiqueta en el chat, un salto más alto o lo que prometa tu pase.
  • Revisa el pase solo en el servidor. Una revisión desde un LocalScript se puede falsificar.
Producto de desarrollador (compras)Da monedas a los jugadores cuando compran un producto de desarrollador, usando ProcessReceipt de forma segura.Script
Tipo
Script (corre en el servidor)
Dónde va
ServerScriptService
Código
-- Developer product handler: ProcessReceipt.
-- Developer products can be bought many times (unlike game passes).
-- Roblox keeps calling ProcessReceipt until you return PurchaseGranted.
-- Needs player.leaderstats.Coins (use the Save data script, or coins are lost when the player leaves).

local Players = game:GetService("Players")
local MarketplaceService = game:GetService("MarketplaceService")
local DataStoreService = game:GetService("DataStoreService")

local receiptStore = DataStoreService:GetDataStore("Receipts_v1")

local function addCoins(player, amount)
	local leaderstats = player:FindFirstChild("leaderstats")
	local coins = leaderstats and leaderstats:FindFirstChild("Coins")
	if not coins then
		return false
	end
	coins.Value += amount
	return true
end

-- [product ID] = function that gives the reward. It must return true if it worked.
local productHandlers = {
	[0] = function(player) -- replace 0 with your developer product ID (100 coins)
		return addCoins(player, 100)
	end,
	-- [0] = function(player) -- another product (1000 coins)
	--	return addCoins(player, 1000)
	-- end,
}

MarketplaceService.ProcessReceipt = function(receiptInfo)
	local player = Players:GetPlayerByUserId(receiptInfo.PlayerId)
	if not player then
		-- The player left. Roblox will ask again when they rejoin.
		return Enum.ProductPurchaseDecision.NotProcessedYet
	end

	-- Has this exact purchase already been given?
	local key = receiptInfo.PlayerId .. "_" .. tostring(receiptInfo.PurchaseId)
	local readOk, alreadyGiven = pcall(function()
		return receiptStore:GetAsync(key)
	end)
	if not readOk then
		return Enum.ProductPurchaseDecision.NotProcessedYet
	end
	if alreadyGiven then
		return Enum.ProductPurchaseDecision.PurchaseGranted
	end

	local handler = productHandlers[receiptInfo.ProductId]
	if not handler then
		warn("No handler for product ID " .. tostring(receiptInfo.ProductId))
		return Enum.ProductPurchaseDecision.NotProcessedYet
	end

	local grantOk, granted = pcall(handler, player)
	if not grantOk or not granted then
		return Enum.ProductPurchaseDecision.NotProcessedYet
	end

	-- Remember the purchase so it is never given twice.
	local writeOk, writeError = pcall(function()
		receiptStore:SetAsync(key, true)
	end)
	if not writeOk then
		warn("Could not record receipt " .. key .. ": " .. tostring(writeError))
	end

	return Enum.ProductPurchaseDecision.PurchaseGranted
end

Cómo ponerlo

  1. En el Creator Dashboard, abre tu juego, entra a Monetization > Developer Products y crea un producto. Copia su ID.
  2. Pon el ID en lugar del 0 en productHandlers. Agrega más entradas para más productos.
  3. Agrega el Script a ServerScriptService. Activa Studio Access to API Services en Game Settings > Security.
  4. Para iniciar una compra, llama a MarketplaceService:PromptProductPurchase(player, productId) desde un botón o un script de ProximityPrompt.

Notas

  • Solo un script de todo tu juego puede definir ProcessReceipt. Si tienes dos, gana el último.
  • Devolver NotProcessedYet es seguro. Roblox lo intentará más tarde, así que el jugador no pierde sus Robux.
  • El almacén de recibos evita dar la recompensa dos veces si Roblox llama a ProcessReceipt dos veces por la misma compra.
  • En un juego real, guarda un registro de compras junto con los datos del jugador si luego quieres reembolsar o revisar.

Flujo del juego

Sistema de checkpointsLos jugadores reaparecen en el último checkpoint que tocaron, con un contador de etapa (Stage).Script
Tipo
Script (corre en el servidor)
Dónde va
ServerScriptService
Código
-- Checkpoint system for an obby.
-- Put your checkpoint Parts in a Folder in the Workspace named "Checkpoints".
-- Name them 1, 2, 3 ... in the order players reach them.

local FOLDER_NAME = "Checkpoints"
local SPAWN_HEIGHT = 4        -- studs above the checkpoint to place the player

local Players = game:GetService("Players")

local folder = workspace:WaitForChild(FOLDER_NAME)

local function getStage(player)
	local leaderstats = player:FindFirstChild("leaderstats")
	if not leaderstats then
		leaderstats = Instance.new("Folder")
		leaderstats.Name = "leaderstats"
		leaderstats.Parent = player
	end

	local stage = leaderstats:FindFirstChild("Stage")
	if not stage then
		stage = Instance.new("IntValue")
		stage.Name = "Stage"
		stage.Value = 0
		stage.Parent = leaderstats
	end
	return stage
end

local function onPlayerAdded(player)
	local stage = getStage(player)

	player.CharacterAdded:Connect(function(character)
		if stage.Value == 0 then
			return -- no checkpoint reached yet; use the normal spawn
		end

		local checkpoint = folder:FindFirstChild(tostring(stage.Value))
		local root = character:WaitForChild("HumanoidRootPart", 5)
		if checkpoint and root then
			character:PivotTo(checkpoint.CFrame + Vector3.new(0, checkpoint.Size.Y / 2 + SPAWN_HEIGHT, 0))
		end
	end)
end

Players.PlayerAdded:Connect(onPlayerAdded)
for _, player in Players:GetPlayers() do
	task.spawn(onPlayerAdded, player)
end

-- Set up each checkpoint.
for _, checkpoint in folder:GetChildren() do
	local number = tonumber(checkpoint.Name)
	if number and checkpoint:IsA("BasePart") then
		checkpoint.Touched:Connect(function(hit)
			local player = Players:GetPlayerFromCharacter(hit.Parent)
			if not player then
				return
			end
			local stage = getStage(player)
			if number > stage.Value then
				stage.Value = number
			end
		end)
	end
end

Cómo ponerlo

  1. En el Workspace, agrega una Folder y llámala Checkpoints.
  2. Pon tus Parts de checkpoint dentro de la carpeta. Renómbralas 1, 2, 3 y así. Pon Anchored en true.
  3. Agrega el Script a ServerScriptService.
  4. Juega. Toca el checkpoint 2 y reinicia tu personaje. Deberías volver en el checkpoint 2.

Notas

  • Los jugadores solo pueden subir. Tocar el checkpoint 1 después del 3 no hace nada.
  • El script agrega un número de Stage a la tabla de posiciones. Comparte la carpeta leaderstats con un script de Coins sin chocar.
  • Stage no se guarda entre visitas. Agrégalo al script de guardar datos si quieres eso.
  • Los nombres de los checkpoints deben ser números simples. Un nombre como Checkpoint1 se ignora.
Temporizador de rondasUn ciclo de espera, descanso y ronda, con el tiempo restante compartido en un StringValue.Script
Tipo
Script (corre en el servidor)
Dónde va
ServerScriptService
Código
-- Round timer: waiting for players -> intermission -> round -> repeat.
-- The time left is written to ReplicatedStorage.RoundStatus (a StringValue).
-- Show it with a GUI that reads that value.

local MIN_PLAYERS = 2
local INTERMISSION_SECONDS = 15
local ROUND_SECONDS = 60
local RESPAWN_AT_ROUND_START = true   -- send everyone to the spawn when the round begins

local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local status = ReplicatedStorage:FindFirstChild("RoundStatus")
if not status then
	status = Instance.new("StringValue")
	status.Name = "RoundStatus"
	status.Parent = ReplicatedStorage
end

local function enoughPlayers()
	return #Players:GetPlayers() >= MIN_PLAYERS
end

local function startRound()
	-- Put your own round code here: pick a map, give weapons, teleport players...
	if RESPAWN_AT_ROUND_START then
		for _, player in Players:GetPlayers() do
			task.spawn(function()
				player:LoadCharacter()
			end)
		end
	end
end

local function endRound()
	-- Put your own end of round code here: show a winner, give rewards...
end

while true do
	-- 1. Wait until enough players are in.
	while not enoughPlayers() do
		status.Value = "Waiting for players (need " .. MIN_PLAYERS .. ")"
		task.wait(1)
	end

	-- 2. Intermission.
	for secondsLeft = INTERMISSION_SECONDS, 1, -1 do
		status.Value = "Next round in " .. secondsLeft
		task.wait(1)
	end

	-- 3. The round.
	if enoughPlayers() then
		startRound()
		for secondsLeft = ROUND_SECONDS, 1, -1 do
			if not enoughPlayers() then
				break
			end
			status.Value = "Round: " .. secondsLeft
			task.wait(1)
		end
		endRound()
	end
end

Cómo ponerlo

  1. Agrega el Script a ServerScriptService.
  2. Para probar solo, pon MIN_PLAYERS en 1.
  3. Juega. Selecciona ReplicatedStorage > RoundStatus en el Explorer y mira cambiar el Value.
  4. Para mostrarlo en pantalla, agrega un TextLabel y un LocalScript que ponga el texto en RoundStatus.Value cada vez que se dispare RoundStatus.Changed.

Notas

  • Pon el código de tu juego en startRound y endRound.
  • player:LoadCharacter() funciona porque Players.CharacterAutoLoads está activado por defecto. Pon RESPAWN_AT_ROUND_START en false si no quieres que todos reaparezcan.
  • La ronda termina antes si se van demasiados jugadores. Cambia esa revisión si tu juego necesita un ganador primero.

Interfaz en pantalla

Cuenta regresiva en pantallaDibuja una cuenta regresiva grande en la pantalla, luego muestra ¡GO! y se oculta.LocalScript
Tipo
LocalScript (corre en el dispositivo del jugador)
Dónde va
StarterPlayer > StarterPlayerScripts
Código
-- Countdown GUI: builds its own ScreenGui and counts down. No setup in the editor.

local START_FROM = 10
local FINISH_TEXT = "GO!"
local HIDE_AFTER = 2          -- seconds the finish text stays on screen
local TEXT_COLOR = Color3.fromRGB(29, 28, 24)

local Players = game:GetService("Players")

local player = Players.LocalPlayer
local playerGui = player:WaitForChild("PlayerGui")

local screenGui = Instance.new("ScreenGui")
screenGui.Name = "CountdownGui"
screenGui.ResetOnSpawn = false      -- keep it when the character resets
screenGui.Parent = playerGui

local label = Instance.new("TextLabel")
label.AnchorPoint = Vector2.new(0.5, 0)
label.Position = UDim2.new(0.5, 0, 0.1, 0)
label.Size = UDim2.new(0, 300, 0, 100)
label.BackgroundTransparency = 1
label.Font = Enum.Font.GothamBold
label.TextSize = 80
label.TextColor3 = TEXT_COLOR
label.TextStrokeTransparency = 0.5
label.Text = tostring(START_FROM)
label.Parent = screenGui

for secondsLeft = START_FROM, 1, -1 do
	label.Text = tostring(secondsLeft)
	task.wait(1)
end

label.Text = FINISH_TEXT
task.wait(HIDE_AFTER)
screenGui:Destroy()

Cómo ponerlo

  1. Abre StarterPlayer y luego StarterPlayerScripts.
  2. Agrega un LocalScript y pega el código.
  3. Juega. Los números bajan en la parte de arriba de la pantalla.
  4. Cambia START_FROM y FINISH_TEXT por lo que necesites.

Notas

  • Cuenta en el dispositivo de cada jugador, así que sirve para cosas como una cuenta de inicio. Para un temporizador compartido de verdad, lee un StringValue que actualice el servidor (mira el script de temporizador de rondas).
  • Pon el script en StarterPlayerScripts, no en StarterGui. Un script directamente en StarterGui vuelve a correr cada vez que el jugador reaparece.
  • Usa un TEXT_COLOR claro para fondos oscuros.
Mensaje de bienvenida en el chatMuestra una línea de bienvenida en la ventana del chat cuando entra un jugador.LocalScript
Tipo
LocalScript (corre en el dispositivo del jugador)
Dónde va
StarterPlayer > StarterPlayerScripts
Código
-- Chat welcome message: a system line in the chat window, shown only to this player.

local MESSAGE = "Welcome to my game! Have fun."

local TextChatService = game:GetService("TextChatService")
local StarterGui = game:GetService("StarterGui")

if TextChatService.ChatVersion == Enum.ChatVersion.TextChatService then
	-- New chat system (the default for new games).
	local channels = TextChatService:WaitForChild("TextChannels", 10)
	local general = channels and channels:WaitForChild("RBXGeneral", 10)
	if general then
		general:DisplaySystemMessage(MESSAGE)
	end
else
	-- Old chat system. The chat may need a moment to load, so try a few times.
	for _ = 1, 10 do
		local ok = pcall(function()
			StarterGui:SetCore("ChatMakeSystemMessage", {
				Text = MESSAGE,
				Color = Color3.fromRGB(255, 220, 80),
			})
		end)
		if ok then
			break
		end
		task.wait(1)
	end
end

Cómo ponerlo

  1. Abre StarterPlayer y luego StarterPlayerScripts.
  2. Agrega ahí un LocalScript y pega el código.
  3. Cambia MESSAGE por tu propio texto de bienvenida.
  4. Juega y abre el chat (el ícono de globo de diálogo, arriba a la izquierda). El mensaje está ahí.

Notas

  • Solo el jugador que entra ve el mensaje. Los demás no.
  • Si el mensaje no aparece, revisa que el chat esté activado en el juego (ajustes de StarterGui y TextChatService).
  • Mantén el mensaje corto. Los largos se parten en varias líneas y se ven desordenados.

Administración y seguridad

Comandos de admin por UserIdComandos de chat como !kill y !speed que solo puedes usar tú y las personas que pongas en la lista.Script
Tipo
Script (corre en el servidor)
Dónde va
ServerScriptService
Código
-- Admin commands for YOUR game. Only the UserIds in the list can use them.
-- Type in chat:  !kill name   !heal name   !speed name 50   !kick name

-- Replace 0 with your Roblox UserId. Add more lines for helpers you trust.
-- Always use the UserId, never the username. Usernames can be changed.
local ADMINS = {
	[0] = true,
}
local PREFIX = "!"

local Players = game:GetService("Players")

-- Finds a player whose name starts with what you typed (not case sensitive).
local function findPlayer(query)
	if not query then
		return nil
	end
	query = string.lower(query)
	for _, player in Players:GetPlayers() do
		if string.sub(string.lower(player.Name), 1, #query) == query then
			return player
		end
	end
	return nil
end

local function getHumanoid(player)
	local character = player.Character
	return character and character:FindFirstChildOfClass("Humanoid")
end

local commands = {}

commands.kill = function(admin, args)
	local target = findPlayer(args[2])
	local humanoid = target and getHumanoid(target)
	if humanoid then
		humanoid.Health = 0
	end
end

commands.heal = function(admin, args)
	local target = findPlayer(args[2])
	local humanoid = target and getHumanoid(target)
	if humanoid then
		humanoid.Health = humanoid.MaxHealth
	end
end

commands.speed = function(admin, args)
	local target = findPlayer(args[2])
	local humanoid = target and getHumanoid(target)
	local speed = tonumber(args[3])
	if humanoid and speed then
		humanoid.WalkSpeed = math.clamp(speed, 0, 100)
	end
end

commands.kick = function(admin, args)
	local target = findPlayer(args[2])
	if target and target ~= admin then
		target:Kick("You were removed by the game admin.")
	end
end

local function onChatted(player, message)
	if not ADMINS[player.UserId] then
		return -- not an admin: ignore silently
	end
	if string.sub(message, 1, #PREFIX) ~= PREFIX then
		return
	end

	local args = string.split(string.sub(message, #PREFIX + 1), " ")
	local command = commands[string.lower(args[1] or "")]
	if command then
		command(player, args)
	end
end

local function onPlayerAdded(player)
	player.Chatted:Connect(function(message)
		onChatted(player, message)
	end)
end

Players.PlayerAdded:Connect(onPlayerAdded)
for _, player in Players:GetPlayers() do
	onPlayerAdded(player)
end

Cómo ponerlo

  1. Busca tu UserId: abre tu perfil de Roblox en el sitio web. El número en la barra de direcciones es tu UserId.
  2. Agrega el Script a ServerScriptService y cambia el 0 de ADMINS por tu UserId.
  3. Haz una prueba con al menos otro jugador (pestaña Test, Clients and Servers, inicia 2 jugadores) o usa tu propio nombre como objetivo.
  4. Escribe !speed tunombre 50 en el chat.

Notas

  • La revisión se hace en el servidor. Los jugadores no pueden darse admin desde su dispositivo.
  • Mientras la lista solo tenga 0, nadie es admin.
  • Para agregar un comando, agrega otro bloque commands.nombre = function(admin, args).
  • Estos comandos son para el juego que tú creaste. Necesitan que tus mensajes de chat lleguen al servidor, que es como funciona el chat de Roblox por defecto.
Reaparecer al caer al vacíoHace reaparecer a los jugadores que caen por debajo del mapa para que no caigan para siempre.Script
Tipo
Script (corre en el servidor)
Dónde va
ServerScriptService
Código
-- Anti-fall: if a player drops below VOID_HEIGHT, they respawn.

local VOID_HEIGHT = -100     -- the Y height under your map. Pick a number lower than the lowest part.
local CHECK_EVERY = 0.5      -- seconds between checks

local Players = game:GetService("Players")

-- Roblox deletes anything below this height anyway (default -500).
-- Making sure our line is above it:
if VOID_HEIGHT <= workspace.FallenPartsDestroyHeight then
	warn("VOID_HEIGHT should be higher than workspace.FallenPartsDestroyHeight")
end

while true do
	for _, player in Players:GetPlayers() do
		local character = player.Character
		local humanoid = character and character:FindFirstChildOfClass("Humanoid")
		local root = character and character:FindFirstChild("HumanoidRootPart")

		if humanoid and root and humanoid.Health > 0 and root.Position.Y < VOID_HEIGHT then
			humanoid.Health = 0   -- the player respawns at their spawn or checkpoint
		end
	end
	task.wait(CHECK_EVERY)
end

Cómo ponerlo

  1. Mira la parte más baja de tu mapa. En la ventana Properties, anota el valor de su Position Y.
  2. Agrega un Script a ServerScriptService y pega el código.
  3. Pon VOID_HEIGHT en un número un poco más bajo que ese valor Y, por ejemplo 50 studs más abajo.
  4. Juega, camina hasta el borde, cae y revisa que reapareces.

Notas

  • Sin esto, los jugadores caen hasta que Roblox los quita en FallenPartsDestroyHeight, que por defecto es -500. Eso tarda un buen rato.
  • Como el jugador muere, funciona junto con el script del sistema de checkpoints. Vuelven a su checkpoint.
  • Un mapa grande con partes a muchas alturas puede necesitar una parte asesina. Este script usa una sola altura para todo el mapa.

Tipos de script en Roblox Studio

TipoDónde correÚsalo para
ScriptEn el servidorTodo lo que debe ser justo: monedas, daño, guardado.
LocalScriptEn el dispositivo de un jugadorTeclas, botones y lo que ve esa persona.
ModuleScriptLo cargan otros scriptsCódigo que se reutiliza. Ninguno de los scripts para principiantes de aquí lo necesita.

Preguntas frecuentes

¿Qué es Luau?

Es el lenguaje de programación que usa Roblox. Se parece mucho a Lua. Todos los scripts de esta página están escritos en Luau y el código se deja tal cual, en inglés, porque así lo lee Roblox Studio.

¿Estos scripts funcionan en juegos de otras personas?

No, y no están hechos para eso. Son scripts normales de Roblox Studio que pones en un juego que tú estás creando.

¿Cuál es la diferencia entre Script, LocalScript y ModuleScript?

Un Script corre en el servidor y sirve para lo que debe ser justo: monedas, daño y guardado. Un LocalScript corre en el dispositivo de un jugador y sirve para teclas, botones y lo que ve esa persona. Un ModuleScript guarda código que cargan otros scripts.

¿Dónde pego el código en Roblox Studio?

Depende del script. Cada uno dice "Dónde va": dentro de una Part, en ServerScriptService o en StarterPlayerScripts. Agrega un script nuevo con el botón de más del Explorer, borra el contenido que trae y pega el código.

¿Por dónde empiezo si soy nuevo?

Con el ladrillo asesino y con Leaderstats (monedas). Son cortos, se entienden fácil y casi todos los demás se apoyan en ideas parecidas.

¿Tengo que traducir el código al español?

No lo hagas. Las palabras de Luau como local, function, if o task.wait tienen que escribirse como están. Lo que sí puedes cambiar son los textos entre comillas que ven los jugadores, como el mensaje de bienvenida.

Mientras armas tu juego, mira el creador de ropa para vestir a tus personajes y la calculadora de impuestos de Robux para ponerle precio a tus pases.

Más herramientas de Roblox