Hi everyone!
I am trying to create a moving platform for a platformer game. I want the platform movement to be client side. Currently, my platform in the workspace has a script attached that runs this code (in the real project I have this ran from a ModuleScript).
local Platform = script.Parent
function Slide(Platform)
local SlideEvent = PlatformEvents:WaitForChild("SlideEvent")
local SlideDistance = Platform:GetAttribute("SlideDistance") or 10
local SlideTime = Platform:GetAttribute("SlideTime") or 2
local function onPlayerAdded(Player)
SlideEvent:FireClient(Player, Platform, SlideDistance, SlideTime)
end
Players.PlayerAdded:Connect(onPlayerAdded)
end
Slide(Platform)
I have a RemoteEvent in ReplicatedStorage that a LocalScript in StarterPlayerScripts is listening to with this code
local function Slide(Platform, SlideDistance, SlideTime)
local TweenService = game:GetService("TweenService")
local RunService = game:GetService("RunService")
-- tween the platform movement
local SlideTweenInfo = TweenInfo.new(SlideTime, Enum.EasingStyle.Cubic, Enum.EasingDirection.InOut, -1, true)
local Tween = TweenService:Create(Platform, SlideTweenInfo, {Position = Platform.Position * Vector3.new(SlideDistance, 0, 0)})
Tween:Play()
-- update velocity with RunService
local PrevPosition = Platform.Position
RunService.Stepped:Connect(function(_, deltaTime)
local CurrentPosition = Platform.Position
local DeltaPosition = CurrentPosition - PrevPosition
local Velocity = DeltaPosition / deltaTime
Platform.AssemblyLinearVelocity = Velocity
PrevPosition = CurrentPosition
end)
end
SlideEvent.OnClientEvent:Connect(Slide)
The error I am having is that when I try to test the game, the LocalScript sees the platform parameter as nil and does nothing. I think this is to do with the player loading before the workspace, so when we call the slide function the platform has not loaded in yet and therefore we send nil. I have tried only sending the event when the player character loads, but I had the same issue. I considered running FireAllClients() on the event rather than just one client but this has the issue of any new player joining after not seeing the platforms moving.
How do I get this to work properly? Thanks in advance for help!