Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I make this local script compatible to server scripts?

Hi all, I was provided this script to make an object look in the direction the mouse is pointing in using CFrame. I understand the script, but the problem is that it runs locally. I want to make it run in a server script, but obviously the GetMouse() and LocalPlayer functions have to be in a local script, so I was suggested to use a remote event. However, I'm not sure how I would in this case, because if I put the lower part of the script (after the defined local variables) into a server script and connect it with a remote event, I will get an error in the server script because mouse and plr must be in local scripts, and thus those variables are not defined in the serv. script. Any solutions? Thanks in advance!

local plr = game.Players.LocalPlayer;  --The player
local mouse = plr:GetMouse();          --The mouse
local obj = workspace.Part1;           --The object

game:GetService("RunService").RenderStepped:connect(function()  
    --CFrame construct  
    local cf = CFrame.new(obj.Position,mouse.Hit.p);
    --Locate the BodyGyro
    local bg = obj:FindFirstChild("BodyGyro");
    --Manipulate it
    bg.P = obj:GetMass()*1000;
    bg.D = 500;
    bg.MaxTorque = Vector3.new(5000,5000,5000);
    bg.CFrame = cf;
end)

1 answer

✓ Accepted answer

You are right, 'mouse' and 'plr' must be defined in a localscript. You calculate the BodyGyro's CFrame on the client, then use the RemoteEvent to send the information to the server.

The InvokeServer function will send any arguments you provide to the server.

local plr = game.Players.LocalPlayer;		-- The player
local mouse = plr:GetMouse();				-- The mouse
local obj = workspace.Part1; 				-- The object
local re = game.ReplicatedStorage.Networking-- The remotevent

game:GetService("RunService").RenderStepped:connect(function()
	--CFrame construct  
	local cf = CFrame.new(obj.Position,mouse.Hit.p);
	--Send server info
	re:FireServer(cf);
end)

Now, you have to set up the connection on the other end. The OnServerEvent event fires whenever FireServer has been called on the specified RemoteEvent. So, use the event to tell the server to set the BodyGyro's CFrame whenever the event recieves some new information.

local re = game.ReplicatedStorage.Networking; 		   -- The remotevent
local bg = workspace.Part1:FindFirstChild("BodyGyro"); -- The BodyGyro

re.OnServerEvent:connect(function(client,cf)
    --Manipulate it
    bg.P = script.Parent:GetMass()*1000;
    bg.D = 500;
    bg.MaxTorque = Vector3.new(5000,5000,5000);
    bg.CFrame = cf;
end)

1 comment

0

Thanks again!

This discussion is preserved as it was. New answers, comments, and votes are closed.