We use cookies on this site to enhance your user experience

BlasterHandler

BlasterHandler

Sep 14 2018, 5:15 PM PST

-- This script handles blaster projectiles on the server-side of the game

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

-- Variables for RemoteEvents and Functions (see the BlasterHandler Script)
local launchProjectile = ReplicatedStorage:WaitForChild("LaunchProjectile")
local destroyProjectile = ReplicatedStorage:WaitForChild("DestroyProjectile")
local destroyEnemy = ReplicatedStorage:WaitForChild("DestroyEnemy")
local pingChecker = ReplicatedStorage:WaitForChild("Ping")

-- This function is called when the client launches a projectile
launchProjectile.OnServerInvoke = function(player, position, velocity)
	-- Make a new projectile and set the velocity
	local projectile = projectileTemplate:Clone()
	projectile.Velocity = velocity
	
	-- Calculate where the projectile should be based on the latency
	-- of the player who launched it
	local ping = 0
	if currentPing[player] then
		ping = currentPing[player]
	end
	local offset = ping * velocity * 1.5
	projectile.Position = position + offset
	
	-- Zero out gravity on the projectile so it doesn't fall through the ground
	local mass = projectile:GetMass()
	projectile.VectorForce.Force = Vector3.new(0, 1, 0) * mass * game.Workspace.Gravity
	
	-- Put the projectile in the workspace and make sure the server is the owner
	projectile.Parent = game.Workspace
	projectile:SetNetworkOwner(nil)
	
	-- Send the projectile back to the player who launched it
	return projectile
end

-- Called when the client detects a projectile should be destroyed
local function onDestroyProjectile(player, projectile)
	projectile:Destroy()
end

-- Called when the client detects an enemy should be destroyed
local function onDestroyEnemy(player, enemy)
	enemy:Destroy()
	-- Give the player a point for destroying an enemy
	local enemyStat = player.leaderstats:WaitForChild("Score")
	enemyStat.Value = enemyStat.Value + 1
end

-- Called when a player joins the game. This function sets up a loop that
-- measures the ping of the player
local function onPlayerAdded(player)
	while player and wait(2) do
		local start = tick()
		pingChecker:InvokeClient(player)
		local ping = tick() - start
		currentPing[player] = ping
	end
end

-- Called when a player leaves the game. Removes their entry from the
-- ping table
local function onPlayerRemoving(player)
	currentPing[player] = nil
end

-- Set up event bindings
destroyProjectile.OnServerEvent:Connect(onDestroyProjectile)
destroyEnemy.OnServerEvent:Connect(onDestroyEnemy)
Players.PlayerAdded:Connect(onPlayerAdded)
Players.PlayerRemoving:Connect(onPlayerRemoving)