My first thought was to ask on Roblox devforum but since imo they got a really messed up admission system, I might as well ask it here.
I've got a tool that shoots a block (wedge) to wherever the mouse is pointing when clicked. It also casts a ray and the block itself sets the health of any humanoid that makes contact with it to 0. But I have got no idea on how to actually implement a cooldown on the gun so you can't just literally spam blocks that kill anything that touches them arround. I think implementing a debounce here is the best option, but I got stuck with that since day 1 and I have no idea how to write it down correctly
I already tried with most of the things that I thought of after visiting this page Roblox dev page about Debounce, also read through some articles that had similar issues in the dev forum, but I can just spam blocks arround whatever I do.
The tool has just two parts (one being the handle) a localscript to wield the parts together, a localscript to catch the mouse position when clicked, two remote events to pass the info from the localscript to the server script and the following server script
local tool = script.Parent
local clickEvent = tool.ClickEvent
local clickEventConnection
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
--Function that creates the part with a touched listener that kills any humanoid that comes into contact with said block
local function createPart(location)
local part = Instance.new("WedgePart")
part.CFrame = location
part.Parent = workspace
part.BrickColor = BrickColor.new("Black")
part.Touched:connect(function(hit)
if hit.Parent then
local hum = hit.Parent:FindFirstChild("Humanoid")
if hum then
hum.Health = 0
end
end
end)
game:GetService("Debris"):AddItem(part, 2)
end
--With the information on the click position of the localscript, this function creates a ray and a beam that accompanies the block, as well as executing the createpart() function on said location
local function onClick(player, clickLocation, ignore)
createPart(clickLocation)
local ray = Ray.new(
tool.Handle.CFrame.p,
(clickLocation.p - tool.Handle.CFrame.p).unit * 500
)
local hit, position, normal = workspace:FindPartOnRay(ray, player.Character, ignore)
local beam = Instance.new("Part", workspace)
if player.Team == Teams["Blue Team"] then
beam.BrickColor = BrickColor.new("Bright blue")
elseif player.Team == Teams["Red Team"] then
beam.BrickColor = BrickColor.new("Bright red")
else
beam.BrickColor = BrickColor.new("Ghost grey")
end
beam.FormFactor = "Custom"
beam.Material = "Neon"
beam.Transparency = 0.25
beam.Anchored = true
beam.Locked = true
beam.CanCollide = false
local distance = (tool.Handle.CFrame.p - position).magnitude
beam.Size = Vector3.new(0.3, 0.3, distance)
beam.CFrame = CFrame.new(tool.Handle.CFrame.p, position) * CFrame.new(0, 0, -distance / 2)
game:GetService("Debris"):AddItem(beam, 1)
end
--subscribing onclick() when equiping the weapon and unsubscribig when unequipping it
local function onEquip()
clickEventConnection = clickEvent.OnServerEvent:connect(onClick)
end
local function onUnequip()
clickEventConnection:disconnect()
end
tool.Equipped:connect(onEquip)
tool.Unequipped:connect(onUnequip)
I just wanted to make a 'cooldown' so a block can be fired each 3 seconds. As is, you can just spam as much as you like to
A simple way to debounce the clicks is to use a variable to decide whether to quickly escape from a function.
You can modify your onClick function so it does not execute if a cooldown is still in place :
-- make a cooldown tracker
local isGunOnCooldown = false
local cooldownTime = 3.0 --seconds
local function onClick(player, clickLocation, ignore)
-- debounce any spammed clicks
if isGunOnCooldown then
return
end
-- put the gun on cooldown
isGunOnCooldown = true
-- fire a bullet
createPart(clickLocation)
local ray = Ray.new(
tool.Handle.CFrame.p,
(clickLocation.p - tool.Handle.CFrame.p).unit * 500)
local hit, position, normal = workspace:FindPartOnRay(ray, player.Character, ignore)
local beam = Instance.new("Part", workspace)
if player.Team == Teams["Blue Team"] then
beam.BrickColor = BrickColor.new("Bright blue")
elseif player.Team == Teams["Red Team"] then
beam.BrickColor = BrickColor.new("Bright red")
else
beam.BrickColor = BrickColor.new("Ghost grey")
end
beam.FormFactor = "Custom"
beam.Material = "Neon"
beam.Transparency = 0.25
beam.Anchored = true
beam.Locked = true
beam.CanCollide = false
local distance = (tool.Handle.CFrame.p - position).magnitude
beam.Size = Vector3.new(0.3, 0.3, distance)
beam.CFrame = CFrame.new(tool.Handle.CFrame.p, position) * CFrame.new(0, 0, -distance / 2)
game:GetService("Debris"):AddItem(beam, 1)
-- start the gun's cooldown and reset it
spawn(function()
wait(cooldown)
isGunOnCooldown = false
end)
end
Related
I have a problem with my Roblox combat system. The problem is that my Animations don't play when I play them. Here are the scripts:
Client Script
local player = game.Players.LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
local UserInputService = game:GetService("UserInputService")
local Debounce = 0.5
local Keybind = Enum.KeyCode.F
local CanPunch = true
local count = 1
local Animations =
{
script:WaitForChild("PunchAnim"),
script:WaitForChild("PunchAnim2")
}
UserInputService.InputBegan:Connect(function(Input, busy)
if Input.KeyCode == Keybind and not busy then
print("Keybind Check")
if CanPunch == true then
print("CanPunch Check")
CanPunch = false
local Anim = char.Humanoid.Animator:LoadAnimation(Animations[count])
Anim:Play()
Anim.Looped = false
count = (count%#Animations) + 1
print("Anim Played")
game.ReplicatedStorage.remotes.Punch:FireServer(player, char)
print("Fired Event")
wait(Debounce)
CanPunch = true
end
end
end)
Server Script
game.Players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(char)
hitbox = Instance.new("Part", workspace)
hitbox.Size = Vector3.new(4,4,4)
hitbox.CanCollide = false
hitbox.Transparency = 1
local weld = Instance.new("Weld", hitbox)
weld.Part0 = char.HumanoidRootPart
weld.Part1 = hitbox
weld.C1 = CFrame.new(0,0,4)
end)
end)
game.ReplicatedStorage.remotes.Punch.OnServerEvent:Connect(function(player, char)
for i, v in pairs(workspace:GetPartsInPart(hitbox)) do
if v.Parent:FindFirstChild("Humanoid") and v.Parent ~= char and v.Parent:FindFirstChild("Hit"..player.Name) == nil then
local Debounce = Instance.new("IntValue", v.Parent)
Debounce.Name = "Hit"..player.Name
game.Debris:AddItem(Debounce, 0.25)
v.Parent:FindFirstChild("Humanoid"):TakeDamage(7.5)
end
end
end)
In the script, I'm telling the Animations to play after F is pressed but when I press it in the game, it doesn't play the animation.
I made this script by watching various tutorials to make my own combat system. I've tried fixing the code by re-watching the tutorials as well as reading the roblox documentation to find a solution but I couldn't find one.
I'm new to Lua and I apologize in advance if this is a very easy and basic question, but all help is appreciated. Also, please point out any other mistake in my script. Thanks.
If you see this question, please answer it if you can.
The answer of my question was, that the animations were R6 but my character was R15. I went and changed the game settings and made it so the game only supported R6.
I'm trying to make something where when you move your mouse, a part moves
When the mouse moves, I want this arm to move and have everything follow just using orientation (and stay at the center of certain parts)
This is my code for moving the parts
-- This is using remote events. This is local
game.ReplicatedStorage.JudgeCam2.OnClientEvent:Connect(function()
game.Workspace.CurrentCamera.CameraType = Enum.CameraType.Scriptable
wait(.1)
local TS = game:GetService("TweenService")
TS:Create(game.Workspace.CurrentCamera, TweenInfo.new(.75,Enum.EasingStyle.Linear,Enum.EasingDirection.Out,0,false,0), {CFrame = game.Workspace.CamParts.JudgeCam2.CFrame}):Play()
local GUN_ICON = "rbxasset://textures/GunCursor.png"
local GUN_RELOAD_ICON = "rbxasset://textures/GunWaitCursor.png"
mouse.Icon = GUN_ICON
local UIS = game:GetService("UserInputService")
local LastMousePos = nil -- Used to calculate how far mouse has moved
UIS.InputChanged:Connect(function(input, gameProcessedEvent)
local CurrentMousePos1 = Vector2.new(mouse.X,mouse.Y)
if gameProcessedEvent then return end
if input.UserInputType == Enum.UserInputType.MouseMovement then -- runs every time mouse is moved
if LastMousePos == nil then
game.ReplicatedStorage.MoveJudge2:FireServer(mouse,CurrentMousePos1,CurrentMousePos1)
else
game.ReplicatedStorage.MoveJudge2:FireServer(mouse,CurrentMousePos1,LastMousePos)
end
LastMousePos = CurrentMousePos1
end
end)
UIS.InputBegan:Connect(function(KeyCode)
if KeyCode.UserInputType == Enum.UserInputType.MouseButton1 and debouce2 == false then
debouce2 = true
mouse.Icon = GUN_RELOAD_ICON
wait(6)
debouce2 = false
end
end)
end)
-- This is the server
game.ReplicatedStorage.MoveJudge2.OnServerEvent:Connect(function(plr, mouse,CurrentMousePos,LastMousePos)
print("(" .. tostring(CurrentMousePos) .. " - " .. tostring(LastMousePos) .. ")/5")
local change = (CurrentMousePos - LastMousePos)/5 -- calculates distance mouse traveled (/5 to lower sensitivity)
game.Workspace.Arm2.CFrame = game.Workspace.Arm2.CFrame * CFrame.Angles(0,math.rad(change.X),-math.rad(change.Y))
end)
Is there any way I can do this with positions or attactments?
Here's the deal, I'm incorporating a teleportation system with a tool on Roblox Studio. However, this error has got me stumped. I will provide the code and other useful sources below and describe the issue after.
local tool = script.Parent.Parent
local debounce = false
local afterTeleport = false
local plrName = game.Players.LocalPlayer.Name
local char = workspace:FindFirstChild(plrName)
tool.Activated:connect(function(m)
if debounce == false then
local hum = game.Players.LocalPlayer.Character.Humanoid
local anim_feet = hum:LoadAnimation(script.Parent.Animation)
local current = anim_feet
local bodyVelocity = tool.Handle.LocalScript.BodyVelocity:Clone()
debounce = true
current:Play()
wait(1.1)
local gui = script.Parent.TransitionGui:Clone()
-- Properties for UI
gui.Parent = game.Players.LocalPlayer.PlayerGui
-- Transition
gui.Frame.BackgroundTransparency = 1
wait(0.02)
gui.Frame.BackgroundTransparency = 0.8
wait(0.02)
gui.Frame.BackgroundTransparency = 0.6
wait(0.02)
gui.Frame.BackgroundTransparency = 0.4
wait(0.02)
gui.Frame.BackgroundTransparency = 0.2
wait(0.02)
gui.Frame.BackgroundTransparency = 0
-- Teleport Player Into Sky Above Them
hum.Parent.HumanoidRootPart.CFrame =
CFrame.new(Vector3.new(hum.Parent.HumanoidRootPart.CFrame.X, hum.Parent.HumanoidRootPart.CFrame.Y + 700, hum.Parent.HumanoidRootPart.CFrame.Z))
bodyVelocity.Parent = hum.Parent.HumanoidRootPart
afterTeleport = true
wait(0.02)
gui.Frame.BackgroundTransparency = 0.2
wait(0.02)
gui.Frame.BackgroundTransparency = 0.4
wait(0.02)
gui.Frame.BackgroundTransparency = 0.6
wait(0.02)
gui.Frame.BackgroundTransparency = 0.8
wait(0.02)
gui.Frame.BackgroundTransparency = 1
wait(0.02)
end
end)
char.Touched:Connect(function(interact)
local hum = game.Players.LocalPlayer.Character.Humanoid
if afterTeleport == true then
if interact:IsA("Terrain") then
if hum.Parent.HumanoidRootPart:FindFirstChild("BodyVelocity") then
hum.Parent.HumanoidRootPart.BodyVelocity:Destroy()
end
elseif interact:IsA("Part") then
if hum.Parent.HumanoidRootPart:FindFirstChild("BodyVelocity") then
hum.Parent.HumanoidRootPart.BodyVelocity:Destroy()
end
elseif interact:IsA("MeshPart") then
if hum.Parent.HumanoidRootPart:FindFirstChild("BodyVelocity") then
hum.Parent.HumanoidRootPart.BodyVelocity:Destroy()
end
end
end
end)
To me, this seems correct. But the issue is whenever I play-test the code, the output displays an error that I don't understand. The output error is:
16:35:59.453 Players.BigBetterBuilder.Backpack.Sky Port.Handle.LocalScript:58: attempt to index nil with 'Touched'
My goal for this tool is that when it is activated, it will teleport you into the sky 700 studs above the players' current position. It will add a BodyVelocity to the player's HumanoidRootPart causing the player to slow down the decent speed, and when the player touched the ground. It should remove the BodyVelocity allowing the player to roam around without having weird gravity.
But the function that's supposed to detect when a player touches the ground isn't working. And I, unfortunately, can't seem to solve the problem.
You've got a timing issue in your code. At the top of your script, you are trying to access the player's character model, but when this script runs, that character might not have been loaded into the workspace yet. So, when you call char.Touched:Connect(...) it throws an error because char is null.
But you've got a different problem as well. The player's character is a Model, and Model's don't have a Touched event like Parts do. So in order to use the Touched event, you either need to attach it to platforms that a character might touch, or to the Parts inside the character model.
So try moving the char.Touched connection inside a callback that fires once the player and character have properly loaded into the game, and attach the Touched connection instead to the different Parts in the character model :
local player = game.Players.LocalPlayer
player.CharacterAdded:Connect(function(character)
-- create a helper function for checking if we're touching the ground
local function checkTouchedGround(interact)
if not afterTeleport then
return
end
local shouldRemoveVelocity = false
if interact:IsA("Terrain") then
shouldRemoveVelocity = true
elseif interact:IsA("Part") then
shouldRemoveVelocity = true
elseif interact:IsA("MeshPart") then
shouldRemoveVelocity = true
end
if shouldRemoveVelocity then
local bv = character.HumanoidRootPart:FindFirstChild("BodyVelocity", 0.1)
if bv then
bv:Destroy()
end
end
end
-- listen for any time any player parts touch the ground
for _, child in ipairs(character:GetDescendants()) do
if child:isA("BasePart") then
child.Touched:Connect(checkTouchedGround)
end
end
end)
I'm trying to make a cutscene sorta thing for a dorr in roblox studio. My solution was to set up a collision detector on the door which would then make a gui template and set its parent to the playergui component.
I did this using the code
local afterIntoTransform = script.Parent.Parent.DoorUnion.Position.Z -6
local afterOutwardsTransform = script.Parent.Parent.DoorUnion.Position.Z + 6
local debounce = false
local function executeFadeSceneAndTpPlayer(player)
local fadeScene = Instance.new("ScreenGui")
local fadeSceneFrame = Instance.new("Frame")
fadeScene.Name = "fadeScene"
fadeSceneFrame.Name = "fadeFrame"
fadeSceneFrame.Size = UDim2.new(1,0,1,0)
fadeSceneFrame.Parent = fadeScene
fadeSceneFrame.BorderSizePixel = 0
fadeSceneFrame.BackgroundColor3 = Color3.new(1, 1, 1)
fadeSceneFrame.BackgroundTransparency = 1
print(game.Players:GetPlayerFromCharacter(player).Name)
fadeScene.Parent = game.Players:GetPlayerFromCharacter(player).PlayerGui
for i = 0, 20, 1 do
fadeSceneFrame.BackgroundTransparency -= 0.05
wait(0.01)
end
player.HumanoidRootPart.Position = Vector3.new(player.HumanoidRootPart.Position.X, player.HumanoidRootPart.Position.Y, afterOutwardsTransform)
for i = 0, 20, 1 do
fadeSceneFrame.BackgroundTransparency += 0.05
wait(0.01)
end
fadeScene:Destroy()
end
script.Parent.Touched:Connect(function(hit)
if not debounce then
debounce = true
executeFadeSceneAndTpPlayer(hit.Parent)
wait(0.2)
debounce = false
end
end)
It tells me: Attempted to index nil with name on line 15.
It works sometimes and sometimes doesnt but recently Ive noticed a trend that I can walk into the door then out again and then it breaks. I haven't coded in a while so I'm a little rusty but I hope I can get some help.
You are running into the same issue as this person : Roblox - attempt to index nil with 'leaderstats'
You are not accounting for the fact that the Touched event fires for every single part that touches it, and some of those parts might not belong to a player.
You can protect against this error by making sure that the object belongs to a player before you call executeFadeSceneAndTpPlayer()
script.Parent.Touched:Connect(function(hit)
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
if not plr then
return
end
if not debounce then
debounce = true
executeFadeSceneAndTpPlayer(hit.Parent)
wait(0.2)
debounce = false
end
end)
My code:
local UIS = game:GetService("UserInputService")
local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
local Activation =
Instance.new("Sound",game.Players.LocalPlayer.Character.Head)
local char = Player.Character
local hum = char.Humanoid
local root = char.HumanoidRootPart
UIS.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.F then
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://1581972610"
local animTrack = hum:LoadAnimation(animation)
animTrack:Play()
Activation.SoundId = "rbxassetid://1581091676" --Plays Mangekyou Sharingan Activation Sound.
Activation:Play()
wait(0.3)
game.Players.LocalPlayer.Character.Head.face.Texture = "rbxassetid://76285632" --When F is pressed, face texture changes to sharingan decal.
game:GetService("Chat"):Chat(Player.Character.Head, "Mangekyou Sharingan!")
end
end)
UIS.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.R then
Activation.SoundId = "rbxassetid://1580990602" --Plays Amaterasu Activation Sound.
Activation:Play()
game:GetService("Chat"):Chat(Player.Character.Head, "Amaterasu!")
local Target = Instance.new("Part") --makes a part
Target.CFrame = Mouse.Hit; --Makes part spawn at the mouse's current location in game
Target.Parent = game.Workspace
Target.Transparency = 1
Target.Anchored = true
Target.CanCollide = false
local Amaterasu = Instance.new("Fire")
Amaterasu.Parent = game.Workspace.Part
Amaterasu.Color = Color3.new(0,0,0)
Amaterasu.SecondaryColor = Color3.new(0,0,0) --amaterasu properties
Amaterasu.Size = 25
local R = Instance.new("RocketPropulsion") --rocket propulsion, parents amaterasu
R.Parent = Amaterasu
R.MaxThrust = 300
R.ThrustP = 30
R:Fire()
end
end)
UIS.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.G then
game.Players.LocalPlayer.Character.Head.face.Texture = "rbxassetid://22557247" --When G is pressed, face texture changes back to normal.(leaves face blank isnt working :/)
end
end)
I am working on the second function in this script, the one that activates if the "r" key is pressed. The function makes a part spawn to the mouses current location with flames inside of it by pressing the "r" key.
This works all fine. I want the flames that spawn to damage any player it touches for a certain amount of health, in this case I want the damage to be 100 health.
I believe what you're looking for is Touched - see Creating a Dangerous Trap: https://wiki.roblox.com/index.php?title=Creating_Traps_and_Pickups
Example provided in documentation:
local trapPart = script.Parent
local function onPartTouch(otherPart)
local partParent = otherPart.Parent
local humanoid = partParent:FindFirstChildWhichIsA("Humanoid")
if ( humanoid ) then
-- Set player's health to 0
humanoid.Health = 0
end
end
trapPart.Touched:Connect(onPartTouch)
But disclaimer - not a Roblox dev (just bugging one right now).
Best of luck.
Don't make your parent before setting properties otherwise it causes performance lag