I'm trying to make realistic bed that when a player touches it a sleeping animation plays but they can still move even tho the player is doing an animation and when the player gets off the bed the animation stops playing
local part = script.Parent --part the script is inside of local sleepanim = part.sleepanimation --the sleeping animation in the part local touched = false part.Touched:Connect(function(hit) local humanoid = hit.Parent.Humanoid if humanoid then touched = true elseif not humanoid then touched = false end end) part.Touched:Connect(function(hit) local humanoid = hit.parent.Humanoid local anim = humanoid:LoadAnimation(sleepanim) if humanoid and touched == true then anim:Play() elseif not humanoid and not touched == true then anim:Stop() end
I have no idea how the script above doesn't work so I need help
Well, I would not suggest you to use Touched
event to detect when the player is not touching an object, because the event won't trigger until something is touching it. Instead , you can use Region3
.
https://developer.roblox.com/en-us/api-reference/datatype/Region3
Example code[It is a Local Script] :
-- Turn the part Collisions off and cover your bed area with a part, CanCollide = false and Transparency of the part = 1 -- Variables -- local Found = false -- A boolean value while wait(1) do -- Loops the code every on second local part = workspace.Part local region = Region3.new(part.Position - (part.Size/2), part.Position + (part.Size/2)) local playerParts = workspace:FindPartsInRegion3WithWhiteList(region, game.Players.LocalPlayer.Character:GetDescendants()) -- Now, we will loop through the playerParts and check whether the player is in the region for _, plr in ipairs(playerParts) do if part:FindFirstAncestor(game.Players.LocalPlayer.Name) then print("Player was found in the region") Found = true break else Found = false print("Player was not found in the region") end end -- Now, we will check if the value is true if Found then -- Alternative is Found == true -- Now, we have to fire to server to do the animation, you can either use RemoteFunction or RemoteEvent. here, we will be using remoteEvent but for safety, you can use RemoteFunction. game.ReplicatedStorage.RemoteEvent:FireServer() end end
Now, I won't be providing the example code for ServerScript, because I believe there won't be no new thing you have to do it there.
Just play the animation on ServerSide and if you want the player to prevent any type of movement, you can just anchor the HumanoidRootPart
, and when the animation ends, you can unanchor it.
Alt : If the anchor didn't work, you can put WalkSpeed
and JumpPower
to 0.
Lemme know if it helps!