Menu
CoddyTech

Pergunte ao Servidor

Lição 6 de 25 do curso Jogo Roblox: Batalhas em Arena da Coddy.

As habilidades começam no dispositivo do jogador. BattleClient é um LocalScript na HUD. ContextActionService associa uma ação a teclas e, com true como terceiro argumento, também coloca um botão para ela na tela do celular:

ContextActionService:BindAction("Wave", use, true, Enum.KeyCode.T)

A função recebe o nome da ação e o estado da entrada, Begin quando a tecla é pressionada. O servidor controla as regras, então o cliente apenas faz uma solicitação por meio do RemoteEvent Remotes.Ability. No servidor, OnServerEvent a recebe, e o Roblox passa primeiro o jogador que a disparou:

remotes.Ability.OnServerEvent:Connect(function(player, name)
	print(name .. " from " .. player.Name)
end)
challenge icon

Desafio

Médio

Faça Q pedir uma investida ao servidor.

  1. Em BattleClient, escreva use(name, state): em Enum.UserInputState.Begin, chame remotes.Ability:FireServer(name).
  2. Vincule-a: ContextActionService:BindAction("Dash", use, true, Enum.KeyCode.Q).
  3. Em BattleServer, conecte remotes.Ability.OnServerEvent a print(player.Name .. " asked for " .. name).

Pressione “Jogar” e pressione Q: a Saída exibirá Player1 asked for Dash. Depois, clique em “Verificar”.

Experimente você mesmo

local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Settings = require(game.ReplicatedStorage.Settings)

local lastSwing = {} -- player -> quando atacou pela última vez

-- As animações de espada do próprio Roblox
local slash = Instance.new("Animation")
slash.AnimationId = "rbxassetid://522635514"

print("Swords deal " .. Settings.SwordDamage .. " damage")

-- Um golpe: a animação e, em seguida, todos na área à sua frente são atingidos
local function swing(player)
	local character = player.Character
	local root = character and character:FindFirstChild("HumanoidRootPart")
	if not root or character.Humanoid.Health <= 0 then
		return
	end
	local now = time()
	if lastSwing[player] and now - lastSwing[player] < Settings.SwingCooldown then
		return
	end
	lastSwing[player] = now
	character.Humanoid.Animator:LoadAnimation(slash):Play()
	-- a área à sua frente, nunca o seu próprio corpo
	local params = OverlapParams.new()
	params.FilterDescendantsInstances = { character }
	local box = root.CFrame * CFrame.new(0, 0, -3)
	local hit = {} -- cada humanoide uma vez por golpe
	for _, part in workspace:GetPartBoundsInBox(box, Settings.HitboxSize, params) do
		local humanoid = part.Parent:FindFirstChildOfClass("Humanoid")
		if humanoid and not hit[humanoid] then
			hit[humanoid] = true
			humanoid:TakeDamage(Settings.SwordDamage)
			print(humanoid.Parent.Name .. " is at " .. humanoid.Health)
		end
	end
end

-- Cada jogador recebe uma espada a cada vida
Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function()
		local sword = ServerStorage.Sword:Clone()
		sword.Parent = player.Backpack
		sword.Activated:Connect(function()
			swing(player)
		end)
	end)
end)

-- O boneco de treino: sua barra de vida acompanha sua vida e, quando é derrotado,
-- o boneco volta após um instante, como uma cópia nova no mesmo lugar
local function setupDummy(dummy)
	local humanoid = dummy.Humanoid
	humanoid.HealthChanged:Connect(function(health)
		dummy.HealthBar.Back.Fill.Size = UDim2.fromScale(health / humanoid.MaxHealth, 1)
	end)
	humanoid.Died:Connect(function()
		local spot = dummy:GetPivot()
		task.wait(0.5)
		dummy:Destroy()
		task.wait(Settings.DummyRespawn)
		local fresh = ServerStorage.Dummy:Clone()
		fresh:PivotTo(spot)
		fresh.Parent = workspace
		setupDummy(fresh)
	end)
end
setupDummy(workspace.Dummy)

Todas as lições de Jogo Roblox: Batalhas em Arena

Pratique por conta própria: Playground de Roblox