Roblox Studio: Nivel Intermedio PGM
馃殌 Introducci贸n al Nivel Intermedio
Ahora que dominas los fundamentos, aprender谩s a escribir c贸digo limpio, eficiente, escalable y mantenible. Este nivel transformar谩 tu enfoque de scripting.
馃幆 Qu茅 Aprender谩s
- Programaci贸n Orientada a Objetos avanzada
- Patrones de dise帽o profesionales
- Comunicaci贸n Cliente-Servidor segura
- Sistemas de juego complejos
- Optimizaci贸n de memoria y rendimiento
馃摎 Requisitos
- Haber completado el nivel b谩sico
- Conocimiento s贸lido de Lua/Luau
- Experiencia con eventos b谩sicos
- Familiaridad con la interfaz de Studio
馃捇 Secci贸n 1: Programaci贸n Avanzada
馃З Programaci贸n Orientada a Objetos
ModuleScripts como Clases
-- En un ModuleScript llamado 'Arma'
local Arma = {}
Arma.__index = Arma
function Arma.new(nombre, da帽o)
local self = setmetatable({}, Arma)
self.nombre = nombre
self.da帽o = da帽o
return self
end
function Arma:atacar()
print("Atacando con "..self.nombre)
end
return Arma
local Arma = {}
Arma.__index = Arma
function Arma.new(nombre, da帽o)
local self = setmetatable({}, Arma)
self.nombre = nombre
self.da帽o = da帽o
return self
end
function Arma:atacar()
print("Atacando con "..self.nombre)
end
return Arma
Uso de Clases
local Arma = require(script.Parent.Arma)
local espada = Arma.new("Espada", 15)
local arco = Arma.new("Arco", 10)
espada:atacar() -- "Atacando con Espada"
arco:atacar() -- "Atacando con Arco"
local espada = Arma.new("Espada", 15)
local arco = Arma.new("Arco", 10)
espada:atacar() -- "Atacando con Espada"
arco:atacar() -- "Atacando con Arco"
馃帹 Patrones de Dise帽o
Singleton
Para sistemas que deben existir una sola vez:
local GameManager = {}
GameManager.__index = GameManager
local instance = nil
function GameManager.getInstance()
if not instance then
instance = setmetatable({}, GameManager)
end
return instance
end
GameManager.__index = GameManager
local instance = nil
function GameManager.getInstance()
if not instance then
instance = setmetatable({}, GameManager)
end
return instance
end
Observer
Sistema de eventos personalizados:
local EventManager = {
listeners = {}
}
function EventManager:on(event, callback)
if not self.listeners[event] then
self.listeners[event] = {}
end
table.insert(self.listeners[event], callback)
end
listeners = {}
}
function EventManager:on(event, callback)
if not self.listeners[event] then
self.listeners[event] = {}
end
table.insert(self.listeners[event], callback)
end
Factory
Creaci贸n de objetos complejos:
local EnemyFactory = {}
function EnemyFactory.create(type)
local enemy = {
type = type,
health = 100
}
-- Configuraci贸n espec铆fica por tipo
return enemy
end
function EnemyFactory.create(type)
local enemy = {
type = type,
health = 100
}
-- Configuraci贸n espec铆fica por tipo
return enemy
end
⚡ Optimizaci贸n y Buenas Pr谩cticas
Gesti贸n de Memoria
- Desconectar eventos con
:Disconnect() - Limpiar referencias a objetos destruidos
- Usar
table.clear()para tablas grandes
Rendimiento
- Evitar bucles anidados innecesarios
- Usar
task.wait()en lugar dewait() - Minimizar operaciones costosas en
Heartbeat
馃攼 Secci贸n 2: Comunicaci贸n Cliente-Servidor
馃攧 Modelo de Replicaci贸n
Lado del Servidor
- Autoridad sobre el estado del juego
- Validaci贸n de todas las acciones
- Manejo de DataStores
- L贸gica cr铆tica del juego
Lado del Cliente
- Interfaz de usuario
- Efectos visuales
- Animaciones locales
- Entrada del jugador
馃摗 RemoteEvents y RemoteFunctions
RemoteEvent
Para comunicaci贸n unidireccional:
-- Servidor
remoteEvent.OnServerEvent:Connect(function(player, data)
-- Validar datos!
if not validateData(data) then return end
-- Procesar acci贸n
end)
remoteEvent.OnServerEvent:Connect(function(player, data)
-- Validar datos!
if not validateData(data) then return end
-- Procesar acci贸n
end)
RemoteFunction
Para solicitudes con respuesta:
-- Servidor
remoteFunction.OnServerInvoke = function(player, data)
-- Validar y procesar
return resultado
end
remoteFunction.OnServerInvoke = function(player, data)
-- Validar y procesar
return resultado
end
馃敀 Seguridad Avanzada
T茅cnicas Clave
- Validaci贸n Estricta: Verificar tipos, rangos y permisos para todos los datos recibidos del cliente
- Rate Limiting: Limitar la frecuencia de mensajes para prevenir spam
- Sanitizaci贸n: Limpiar entradas de texto para prevenir inyecci贸n
- Encriptaci贸n: Para datos sensibles usando HTTPService
馃洜️ Secci贸n 3: Servicios Avanzados
馃幀 TweenService
Animaciones fluidas de propiedades:
local TweenService = game:GetService("TweenService")
local tweenInfo = TweenInfo.new(
1, -- Duraci贸n
Enum.EasingStyle.Quad, -- Estilo
Enum.EasingDirection.Out -- Direcci贸n
)
local tween = TweenService:Create(part, tweenInfo, {Position = Vector3.new(0,10,0)})
tween:Play()
local tweenInfo = TweenInfo.new(
1, -- Duraci贸n
Enum.EasingStyle.Quad, -- Estilo
Enum.EasingDirection.Out -- Direcci贸n
)
local tween = TweenService:Create(part, tweenInfo, {Position = Vector3.new(0,10,0)})
tween:Play()
馃椇️ PathfindingService
Navegaci贸n para NPCs:
local PathfindingService = game:GetService("PathfindingService")
local path = PathfindingService:CreatePath({
AgentRadius = 2,
AgentHeight = 5
})
path:ComputeAsync(npc.Position, destino)
local waypoints = path:GetWaypoints()
-- Seguir waypoints
local path = PathfindingService:CreatePath({
AgentRadius = 2,
AgentHeight = 5
})
path:ComputeAsync(npc.Position, destino)
local waypoints = path:GetWaypoints()
-- Seguir waypoints
馃捑 DataStores
Guardado de datos persistente:
local DataStoreService = game:GetService("DataStoreService")
local store = DataStoreService:GetDataStore("PlayerData")
local function saveData(player)
local success, err = pcall(function()
store:UpdateAsync(player.UserId, function(old)
return player.Data -- Datos actualizados
end)
end)
-- Manejar errores
end
local store = DataStoreService:GetDataStore("PlayerData")
local function saveData(player)
local success, err = pcall(function()
store:UpdateAsync(player.UserId, function(old)
return player.Data -- Datos actualizados
end)
end)
-- Manejar errores
end
馃彿️ CollectionService
Gesti贸n de objetos por tags:
local CollectionService = game:GetService("CollectionService")
-- A帽adir tag a un objeto
CollectionService:AddTag(part, "Enemigo")
-- Obtener todos con tag
local enemigos = CollectionService:GetTagged("Enemigo")
-- Escuchar nuevos objetos con tag
CollectionService:GetInstanceAddedSignal("Enemigo"):Connect(function(obj)
-- Configurar nuevo enemigo
end)
-- A帽adir tag a un objeto
CollectionService:AddTag(part, "Enemigo")
-- Obtener todos con tag
local enemigos = CollectionService:GetTagged("Enemigo")
-- Escuchar nuevos objetos con tag
CollectionService:GetInstanceAddedSignal("Enemigo"):Connect(function(obj)
-- Configurar nuevo enemigo
end)
馃幃 Secci贸n 4: Sistemas de Juego Avanzados
馃帓 Sistema de Inventario
Estructura de Datos
local Inventory = {}
Inventory.__index = Inventory
function Inventory.new(slots)
local self = setmetatable({}, Inventory)
self.slots = slots -- N煤mero de espacios
self.items = {} -- Tabla de 铆tems
return self
end
Inventory.__index = Inventory
function Inventory.new(slots)
local self = setmetatable({}, Inventory)
self.slots = slots -- N煤mero de espacios
self.items = {} -- Tabla de 铆tems
return self
end
M茅todos Clave
function Inventory:addItem(itemId, quantity)
for _, slot in pairs(self.items) do
if slot.id == itemId then
slot.quantity += quantity
return true
end
end
-- A帽adir a nuevo slot
end
for _, slot in pairs(self.items) do
if slot.id == itemId then
slot.quantity += quantity
return true
end
end
-- A帽adir a nuevo slot
end
馃 IA para NPCs
M谩quina de Estados
local states = {
IDLE = 1,
PATROL = 2,
CHASE = 3,
ATTACK = 4
}
function NPC:updateState()
if self.state == states.IDLE then
-- L贸gica idle
elseif self.state == states.CHASE then
-- Perseguir jugador
end
end
IDLE = 1,
PATROL = 2,
CHASE = 3,
ATTACK = 4
}
function NPC:updateState()
if self.state == states.IDLE then
-- L贸gica idle
elseif self.state == states.CHASE then
-- Perseguir jugador
end
end
Detecci贸n
function NPC:checkSight()
local rayParams = RaycastParams.new()
rayParams.FilterDescendantsInstances = {self.model}
local ray = Ray.new(
self.head.Position,
(player.Character.Head.Position - self.head.Position).Unit * 50
)
local hit = workspace:Raycast(ray.Origin, ray.Direction, rayParams)
return hit and hit.Instance:IsDescendantOf(player.Character)
end
local rayParams = RaycastParams.new()
rayParams.FilterDescendantsInstances = {self.model}
local ray = Ray.new(
self.head.Position,
(player.Character.Head.Position - self.head.Position).Unit * 50
)
local hit = workspace:Raycast(ray.Origin, ray.Direction, rayParams)
return hit and hit.Instance:IsDescendantOf(player.Character)
end
⚔️ Sistema de Combate
Hitboxes
function Weapon:checkHit()
local hitbox = self.model.Hitbox
local parts = workspace:GetPartsInPart(hitbox)
for _, part in pairs(parts) do
local humanoid = part.Parent:FindFirstChild("Humanoid")
if humanoid then
humanoid:TakeDamage(self.damage)
end
end
end
local hitbox = self.model.Hitbox
local parts = workspace:GetPartsInPart(hitbox)
for _, part in pairs(parts) do
local humanoid = part.Parent:FindFirstChild("Humanoid")
if humanoid then
humanoid:TakeDamage(self.damage)
end
end
end
Da帽o y Efectos
-- Servidor
function applyDamage(attacker, target, damage)
local humanoid = target:FindFirstChild("Humanoid")
if humanoid then
humanoid:TakeDamage(damage)
-- Replicar efectos
remoteEvent:FireAllClients("ShowDamage", target, damage)
end
end
function applyDamage(attacker, target, damage)
local humanoid = target:FindFirstChild("Humanoid")
if humanoid then
humanoid:TakeDamage(damage)
-- Replicar efectos
remoteEvent:FireAllClients("ShowDamage", target, damage)
end
end
馃洜️ Secci贸n 5: Herramientas Profesionales
馃攧 Control de Versiones
- Historial de Cambios: Revertir a versiones anteriores
- Colaboraci贸n: Trabajar en equipo sin conflictos
- Ramas: Desarrollar features independientes
馃攲 Plugins Esenciales
- Rojo: Depuraci贸n avanzada
- GapFill: Construcci贸n r谩pida
- Material Generator: Texturas personalizadas
馃悶 Depuraci贸n Avanzada
Breakpoints
Pausar ejecuci贸n en puntos espec铆ficos
Step Through
Ejecutar l铆nea por l铆nea
Watch Variables
Monitorear valores en tiempo real
⚡ An谩lisis de Rendimiento
local stats = game:GetService("Stats")
print("Memory:", stats:GetMemoryUsageMb())
print("FPS:", stats:GetFps())
print("Memory:", stats:GetMemoryUsageMb())
print("FPS:", stats:GetFps())
⭐ Proyecto Final: RPG B谩sico
Combina todo lo aprendido en un juego funcional con m煤ltiples sistemas interconectados
馃幆 Requisitos Completos
馃З Sistemas Obligatorios
- Sistema de inventario con capacidad limitada
- 3 tipos de enemigos con IA b谩sica
- Sistema de combate con hitboxes
- Guardado de progreso con DataStores
- Interfaz de usuario funcional
✨ Elementos Avanzados
- M谩quina de estados para NPCs
- Animaciones con TweenService
- Sistema de di谩logos
- Efectos de sonido contextuales
- Optimizaci贸n de rendimiento
馃摐 Estructura de Clases
local PlayerClass = {}
PlayerClass.__index = PlayerClass
function PlayerClass.new(player)
local self = setmetatable({}, PlayerClass)
self.player = player
self.inventory = Inventory.new(20)
return self
end
PlayerClass.__index = PlayerClass
function PlayerClass.new(player)
local self = setmetatable({}, PlayerClass)
self.player = player
self.inventory = Inventory.new(20)
return self
end
馃幃 Eventos Principales
-- Servidor
Players.PlayerAdded:Connect(function(player)
local playerObj = PlayerClass.new(player)
playerObj:loadData()
setupPlayerEvents(playerObj)
end)
Players.PlayerAdded:Connect(function(player)
local playerObj = PlayerClass.new(player)
playerObj:loadData()
setupPlayerEvents(playerObj)
end)
© 2025 Tips Roblox Studio | Todos los derechos reservados
Comentarios
Publicar un comentario