Roblox, damaging a player upon contact with a part - lua

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

Related

How to aim a gun where the camera is pointing?

I have a fixed "Over-The-Shoulder" camera system, and i want to aim the gun where the camera is pointing at.
My best bet was to use the CFrame.Rotation, but it didn't work so well.
That's when i tried, getting the angles from the camera every time it changed, using: workspace.CurrentCamera.Change:Connect, and then applying the rotation vectors (Camera.CFrame.Rotation) to the entire of the player's body.
Then i've tried implementing Inverse Kinematics, to my code, but honestly, i could not stand copied code that i don't know how it works, so i scraped everything that i've copied.
Everything that i found about IK (Inverse Kinematics), was little to no useful, since no one really did what i want to achieve.
I don't know if it's achievable or not, but, if it helps, here is the state of my code, and an example image.
-- Script for controling the player camera.
-- Used for aiming in general.
-- Game global table
local globals = require(game.ReplicatedStorage.globalStates)
-- Normal services
local UserInputService, runService = game:GetService("UserInputService"), game:GetService("RunService")
local LocalPlayer = game:GetService("Players").LocalPlayer -- Get client's player
local Camera = game:GetService("Workspace").CurrentCamera -- Player's camera(?)
local TweenService = game:GetService("TweenService")
local PlayerMouse = LocalPlayer:GetMouse()
local DEF_FOV = 70
local AIM_FOV = 35
local AIM_SENS = 0.3
local AIM_DURR_TIME = 0.15
local xAngle, yAngle = 0, 0
local cameraOffset = Vector3.new(3.5, 0, 7.5)
local tweenIn = TweenService:Create(Camera, TweenInfo.new(AIM_DURR_TIME), {FieldOfView = AIM_FOV})
local tweenOut = TweenService:Create(Camera, TweenInfo.new(AIM_DURR_TIME), {FieldOfView = DEF_FOV})
-- TODO: Fix bug when player changes camera mode in menu
wait(1)
Camera.CameraType = Enum.CameraType.Scriptable -- Used for creating custom behavior
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter -- Lock the cursor
PlayerMouse.Icon = "rbxassetid://9095360160" -- Set dot crosshair
UserInputService.InputChanged:Connect(function(input)
if input.UserInputType == Enum.UserInputType.MouseMovement then
xAngle = xAngle - input.Delta.x * 0.4
yAngle = math.clamp(yAngle - input.Delta.y * 0.4, -80, 80)
end
end)
-- This will run every frame
runService.RenderStepped:Connect(function()
local Character = LocalPlayer.Character
local Root = LocalPlayer.Character:FindFirstChild("HumanoidRootPart")
if Character and Root then
local startCFrame = CFrame.new((Root.CFrame.p + Vector3.new(0,2,0))) * CFrame.Angles(0, math.rad(xAngle), 0) * CFrame.Angles(math.rad(yAngle), 0, 0)
local cameraCFrame = startCFrame + startCFrame:vectorToWorldSpace(Vector3.new(cameraOffset.X,cameraOffset.Y,cameraOffset.Z))
local cameraFocus = startCFrame + startCFrame:vectorToWorldSpace(Vector3.new(cameraOffset.X,cameraOffset.Y,-50000))
Camera.CFrame = CFrame.new(cameraCFrame.p ,cameraFocus.p)
end
end)
-- Only 'aim' if TOGGLE_MOUSE and TOGGLE_MOUSE are false
PlayerMouse.Button2Down:Connect(function()
if globals.TOGGLE_MOUSE == false and globals.IS_PLAYER_AIMING == false then
tweenIn:Play()
globals.IS_PLAYER_AIMING = true
else
print("Could not start player aim")
end
end)
PlayerMouse.Button2Up:Connect(function()
tweenOut:Play()
globals.IS_PLAYER_AIMING = false
end)

How to move multiple parts with attachments

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?

How to fix my combat script when no errors are showing?

I have created this script in hopes of creating a combat system that can play multiple animations in one button; however, when I put them in the light attack section of the script, the animations will not play, yet I have no errors in my code.
I have tried reorganizing, using the actual animation ids, changing variable names, etc.
local Player = game.Players.LocalPlayer
local Character = script.Parent
local Humanoid = Character.Humanoid
AnimationId1 = "rbxassetid://2046787868"
AnimationId2 = "rbxassetid://2046881922"
AnimationId3 = "rbxassetid://"
AnimationId4 = "rbxassetid://2048242167"
Debounce = true
local Key = 'U'
local Key2 = 'I'
local Key3 = 'O'
local Key4 = 'P'
local UserInputService = game:GetService("UserInputService")
--Animation for the Light attk combo sequence.
UserInputService.InputBegan:connect(function(Input, IsTyping)
for i, v in pairs(game.Players:GetChildren()) do
if Input.KeyCode == Enum.KeyCode[Key] then
local Animation = Instance.new("Animation")
Animation.AnimationId = AnimationId1, AnimationId2
local LoadAnimation = Humanoid:LoadAnimation(Animation)
if v == 1 then
LoadAnimation:Play(AnimationId1)
elseif v == 2 then
LoadAnimation:Play(AnimationId2)
end
end
end
end)
--Animation for the Blocking sequence.
UserInputService.InputBegan:connect(function(Input, IsTyping)
if IsTyping then return end
if Input.KeyCode == Enum.KeyCode[Key4] and Debounce then
Debounce = false
local Animation = Instance.new("Animation")
Animation.AnimationId = AnimationId4
local LoadAnimation = Humanoid:LoadAnimation(Animation)
LoadAnimation:Play()
wait(.5)
LoadAnimation:Stop()
Debounce = true
end
end)
The blocking part of this script works perfectly, however, when I try to use the light attack section, it doesn't work.
In your light attack function, v is a Player object. So any check like v == 1 or v == 2 will fail because it is the wrong type. It also doesn't really make sense that you would iterate over all of the players when they press the 'U' button.
You can make it play an animation just like you did with your blocking animation code.
-- make a counter to help decide which animation to play
local swingCount = 0
local currentSwingAnimation
--Animation for the Light attack combo sequence.
UserInputService.InputBegan:connect(function(Input, IsTyping)
if IsTyping then return end
if Input.KeyCode == Enum.KeyCode[Key] then
swingCount = swingCount + 1
-- cancel any animation currently playing
if currentSwingAnimation then
currentSwingAnimation:Stop()
currentSwingAnimation = nil
end
if swingCount == 1 then
-- play the first animation
local Animation = Instance.new("Animation")
Animation.AnimationId = AnimationId1
currentSwingAnimation = Humanoid:LoadAnimation(Animation)
currentSwingAnimation.Looped = false
currentSwingAnimation:Play()
elseif swingCount == 2 then
-- play the second swing animation
local Animation = Instance.new("Animation")
Animation.AnimationId = AnimationId2
currentSwingAnimation = Humanoid:LoadAnimation(Animation)
currentSwingAnimation.Looped = false
currentSwingAnimation:Play()
-- reset the swing counter to start the combo over
swingCount = 0
end
end
end)

How can I implement a debounce in this code

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

Roblox making functions run more than once

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 except after the first time I press "r" to spawn the part at my mouse location, if I move my mouse's location to another area and press "r" again it repeats everything in the function but doesn't change to the new location.
You should try running Mouse = Player:GetMouse() inside your function that runs if they press the R key, to update the mouse's location. Your updated event would look like:
UIS.InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.R then
Mouse = Player:GetMouse() --This line updates the mouse and presumably, its location.
Activation.SoundId = "rbxassetid://1580990602"Sound.
Activation:Play()
game:GetService("Chat"):Chat(Player.Character.Head, "Amaterasu!")
local Target = Instance.new("Part")
Target.CFrame = Mouse.Hit;
--All the other stuff you're doing goes here
This way, the mouse's location is updated every time the if block is entered (which is every time the user presses R).

Resources