Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

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

Asked by 7 years ago

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

Log in to vote
0
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
7 years ago
Edited 7 years ago

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)
0
Thanks again! SilentAim 36 — 7y
Ad

Answer this question