How to make ContextActionAction Gun Fire

hello everyone :raised_hand_with_fingers_splayed:

I just want to ask for help from you guys.
i have trouble creating ContextActionService Fire. can you guys help me???
I’ve tried my best to create a ContextActionService but always fail

Script Guns:

local localPlayer = game.Players.LocalPlayer
local sp=script.Parent

local Player = game.Players.LocalPlayer
local c = Player.Character
if not c or not c.Parent then
	c = Player.CharacterAdded:wait()
end

sp:WaitForChild("Handle")
sp:WaitForChild("Ammo")

sp.Handle:WaitForChild("Equip")
sp.Handle:WaitForChild("Fire")
sp.Handle:WaitForChild("Reload")
sp.Handle:WaitForChild("Trigger")
sp.Handle:WaitForChild("PointLight")
sp.Flare:WaitForChild("BillboardGui")

local CanTeamkill = false
local FirstPersonArms = true
local HeadshotDamage = true
local IgnoreHats = true

local ClipSize=30
local ReloadTime=2.3
local Firerate=.14
local MinSpread=0.15
local MaxSpread=0.15
local SpreadRate=0.3
local BaseDamage= 38
local Spread=0.15
local automatic=true
local burst=false
local shot=false			--Shotgun
local BarrlePos=Vector3.new(-2.5,.60,0)
local Cursors={"rbxasset://textures\\GunCursor.png"}
local ReloadCursor="rbxasset://textures\\GunWaitCursor.png"
-------------------------------------
local equiped=false


local enabled=true
local reloading=false
local down=false
local r=game:service("RunService")

local Ans = {}

local function Load(h)
	Ans["Hold"] = h:LoadAnimation(script.Parent.Hold)
	Ans["Fire"] = h:LoadAnimation(script.Parent.Fire)
	Ans["Reload"] = h:LoadAnimation(script.Parent.Reload)
end

local function Play(a,speed)
	if Ans[a] then
		Ans[a]:Play(nil,nil,speed)
	end
end

local function Stop(a)
	if Ans[a] then
		Ans[a]:Stop()
	end
end



local Bullet=Instance.new("Part")
Bullet.Name="Bullet"
Bullet.BrickColor=BrickColor.new("Institutional white")
Bullet.Anchored=true
Bullet.CanCollide=false
Bullet.Locked=true
Bullet.Size=Vector3.new(1,1,1)
Bullet.formFactor=0
Bullet.TopSurface=0
Bullet.BottomSurface=0
Bullet.Transparency= 0.9
Bullet.Material = Enum.Material.Neon
local Mesh=Instance.new("SpecialMesh")
Mesh.Parent=Bullet
Mesh.MeshType="Brick"
Mesh.Name="Mesh"
Mesh.Scale=Vector3.new(.15,.15,1)

local pointLight = sp.Handle.PointLight
local BillboardGui = sp.Flare.BillboardGui
local Debris = game:GetService("Debris")
local flare = script.Parent:WaitForChild("Flare")

local gunServer = game:GetService("ReplicatedStorage"):WaitForChild("GunRemotes")

local remote = {
	TagHumanoid = gunServer:WaitForChild("TagHumanoid"),
	FireServer = gunServer:WaitForChild("FireServer"),
	TakeDamage = gunServer:WaitForChild("TakeDamage"),
	PlaySound = gunServer:WaitForChild("PlaySound"),
}
local ContextActionService = game:GetService("ContextActionService")


game.Workspace.ChildAdded:Connect(function(child)
	if child.Name == localPlayer.Name.."Bullet" then
		child.Transparency = 0.6
	end
end)

local function reload(mouse)
	Play("Reload",.7)
	remote.PlaySound:FireServer(sp.Handle.Reload)
	reloading=true
	mouse.Icon=ReloadCursor
	while sp.Ammo.Value<ClipSize and reloading and enabled do
		wait(ReloadTime/ClipSize)
		if reloading then
			sp.Ammo.Value=sp.Ammo.Value+1
		else
			break
		end
	end
	mouse.Icon=Cursors[1]
	reloading=false
end

local function reload_Mob()
	reloading=false
	while sp.Ammo.Value<ClipSize and reloading and enabled do
		wait(ReloadTime/ClipSize)
		if reloading then
			sp.Ammo.Value=sp.Ammo.Value+1
		else
			break
		end
	end
	reloading=false
end

local function onKeyDown(key,mouse)
	key=key:lower()
	if key=="r" and not reloading then
		reload(mouse)
	end
end

function onButtonPress(button)
	wait(0.1)	
	if onButtonPress() and not reloading then
	if script.Parent.Ammo.Value < 30 then
		wait(0.1)
		reload_Mob()
	end
		script.Parent:reload(button)
	end
end	



local function getIgnoreList()
	local list = {localPlayer.Character}
	for _,child in pairs(game.Workspace:GetDescendants()) do
		if child:IsA("BasePart") then
			if not child.CanCollide then
				if child.Name == "Handle" and IgnoreHats then
					table.insert(list,child)
				elseif child.Name ~= "Handle" and not child.Parent:FindFirstChild("Humanoid") then
					table.insert(list,child)
				end
			end
		end
	end
	return list
end

local function bulletEffect(bullet,distance)
	if distance > 40 then
		local bulletLength = distance/2
		bullet.Mesh.Scale=Vector3.new(.15,.15,bulletLength)
		bullet.Mesh.Offset=Vector3.new(0,0,bulletLength/2)
		while bullet.Mesh.Offset.Z > (bulletLength/2)*-1 do
			wait()
			bullet.Mesh.Offset=Vector3.new(0,0,bullet.Mesh.Offset.Z-20) 
		end
	else
		bullet.Mesh.Scale=Vector3.new(.15,.15,distance)
		bullet.Mesh.Offset=Vector3.new(0,0,distance/2)
		wait(0.03)
	end
	bullet:Destroy()
end

local function fire(aim)
	Play("Fire")
	if sp.Parent.Humanoid.Health < 1 then
		return
	end
	remote.PlaySound:FireServer(sp.Handle.Fire)
	
	t=r.Stepped:wait()
	last6=last5
	last5=last4
	last4=last3
	last3=last2
	last2=last
	last=t
	local bullet=Bullet:clone()
	local startpoint=sp.Handle.CFrame*BarrlePos
	local ray = Ray.new(startpoint, (aim - startpoint).unit * 300)
	local hit, position = workspace:FindPartOnRayWithIgnoreList(ray, getIgnoreList(), false, true)
	local distance = (startpoint - position).magnitude
	bullet.Parent=game.Workspace.CurrentCamera
	
	remote.FireServer:FireServer(startpoint,position,pointLight)
	remote.FireServer:FireServer(startpoint,position,BillboardGui)

	if hit~=nil then
		local humanoid=hit.Parent:FindFirstChild("Humanoid")
		if not humanoid then
			humanoid = hit.Parent.Parent:FindFirstChild("Humanoid")
		end
		if humanoid~=nil then
			local damage=math.random(BaseDamage-(BaseDamage*.25),BaseDamage+(BaseDamage*.25))
			local headshot = false
			if hit.Name=="Head" and HeadshotDamage then
				damage=damage*1.3
				--headshot = true
			else
				damage=damage*.75
			end
			if humanoid.Health>0 then
				local eplr=game.Players:playerFromCharacter(humanoid.Parent)
				local plr=game.Players:playerFromCharacter(sp.Parent)
				if eplr~=nil and plr~=nil then
					if CanTeamkill then
						remote.TagHumanoid:FireServer(humanoid)
						remote.TakeDamage:FireServer(humanoid,damage,headshot)
					else
						if eplr.TeamColor~=plr.TeamColor or eplr.Neutral or plr.Neutral then
							remote.TagHumanoid:FireServer(humanoid)
							remote.TakeDamage:FireServer(humanoid,damage,headshot)
						end	
					end
				else
					remote.TagHumanoid:FireServer(humanoid)
					remote.TakeDamage:FireServer(humanoid,damage,headshot)
				end
			end
		end
	end
	if distance > 40 then
		bullet.CFrame=CFrame.new(startpoint, position) * CFrame.new(0, 0, -distance / 2)
	else
		bullet.CFrame=CFrame.new(startpoint, position) * CFrame.new(0, 0, -distance)
	end
	spawn(function()
		bulletEffect(bullet,distance)
	end)
end


local ObjectLocalTransparencyModifier
local RunService = game:GetService("RunService")
local LocalObjects = {}
local function setArmsTransparency(Limb)
	if FirstPersonArms then
		local value = {Object = Limb, Transparency = 0, AutoUpdate = true}	
		pcall(function()
			local ObjectFound = false
			for i, v in pairs(LocalObjects) do
				if v == value then
					ObjectFound = true
				end
			end
			if not ObjectFound then
				table.insert(LocalObjects, value)
				if ObjectLocalTransparencyModifier then
					ObjectLocalTransparencyModifier:disconnect()
				end
				ObjectLocalTransparencyModifier = RunService.RenderStepped:connect(function()
					local Camera = game:GetService("Workspace").CurrentCamera
					for i, v in pairs(LocalObjects) do
						if v.Object and v.Object.Parent then
							local CurrentTransparency = v.Object.LocalTransparencyModifier
							local ViewDistance = (Camera.CoordinateFrame.p - sp.Parent.Head.Position).Magnitude
							if ((not v.AutoUpdate and (CurrentTransparency == 1 or CurrentTransparency == 0)) or v.AutoUpdate) then
								if ((v.Distance and ViewDistance <= v.Distance) or not v.Distance) then
									v.Object.LocalTransparencyModifier = v.Transparency
								else
									v.Object.LocalTransparencyModifier = 0
								end
							end
						else
							table.remove(LocalObjects, i)
						end
					end
				end)
			end
		end)
	end
end

local function onButton1Up(mouse)
	down=false
end

local  function onButton1Down(mouse)
	local h=sp.Parent:FindFirstChild("Humanoid")
	if not enabled or reloading or down or h==nil then
		return
	end
	if sp.Ammo.Value>0 and h.Health>0 then
		down=true
		enabled=false
		while down do
			if sp.Ammo.Value<=0 then
				break
			end
			if burst then
				local startpoint=sp.Handle.CFrame*BarrlePos
				local mag=(mouse.Hit.p-startpoint).magnitude
				local rndm=Vector3.new(math.random(-(Spread/10)*mag,(Spread/10)*mag),math.random(-(Spread/10)*mag,(Spread/10)*mag),math.random(-(Spread/10)*mag,(Spread/10)*mag))
				fire(mouse.Hit.p+rndm)
				sp.Ammo.Value=sp.Ammo.Value-1
				if sp.Ammo.Value<=0 then
					break
				end
				wait(.05)
				local startpoint=sp.Handle.CFrame*BarrlePos
				local mag2=((mouse.Hit.p+rndm)-startpoint).magnitude
				local rndm2=Vector3.new(math.random(-(.1/10)*mag2,(.1/10)*mag2),math.random(-(.1/10)*mag2,(.1/10)*mag2),math.random(-(.1/10)*mag2,(.1/10)*mag2))
				fire(mouse.Hit.p+rndm+rndm2)
				sp.Ammo.Value=sp.Ammo.Value-1
				if sp.Ammo.Value<=0 then
					break
				end
				wait(.05)
				fire(mouse.Hit.p+rndm+rndm2+rndm2)
				sp.Ammo.Value=sp.Ammo.Value-1
			elseif shot then
				sp.Ammo.Value=sp.Ammo.Value-1
				local startpoint=sp.Handle.CFrame*BarrlePos
				local mag=(mouse.Hit.p-startpoint).magnitude
				local rndm=Vector3.new(math.random(-(Spread/10)*mag,(Spread/10)*mag),math.random(-(Spread/10)*mag,(Spread/10)*mag),math.random(-(Spread/10)*mag,(Spread/10)*mag))
				fire(mouse.Hit.p+rndm)
				local mag2=((mouse.Hit.p+rndm)-startpoint).magnitude
				local rndm2=Vector3.new(math.random(-(.2/10)*mag2,(.2/10)*mag2),math.random(-(.2/10)*mag2,(.2/10)*mag2),math.random(-(.2/10)*mag2,(.2/10)*mag2))
				fire(mouse.Hit.p+rndm+rndm2)
				local rndm3=Vector3.new(math.random(-(.2/10)*mag2,(.2/10)*mag2),math.random(-(.2/10)*mag2,(.2/10)*mag2),math.random(-(.2/10)*mag2,(.2/10)*mag2))
				fire(mouse.Hit.p+rndm+rndm3)
				local rndm4=Vector3.new(math.random(-(.2/10)*mag2,(.2/10)*mag2),math.random(-(.2/10)*mag2,(.2/10)*mag2),math.random(-(.2/10)*mag2,(.2/10)*mag2))
				fire(mouse.Hit.p+rndm+rndm4)
			else
				sp.Ammo.Value=sp.Ammo.Value-1
				local startpoint=sp.Handle.CFrame*BarrlePos
				local mag=(mouse.Hit.p-startpoint).magnitude
				local rndm=Vector3.new(math.random(-(Spread/10)*mag,(Spread/10)*mag),math.random(-(Spread/10)*mag,(Spread/10)*mag),math.random(-(Spread/10)*mag,(Spread/10)*mag))
				fire(mouse.Hit.p+rndm)
			end
			wait(Firerate)
			if not automatic then
				break
			end
		end	
		enabled=true
		flare.BillboardGui.Enabled = false
	else
		remote.PlaySound:FireServer(sp.Handle.Trigger)
	end
end

local function onEquippedLocal(mouse)
	remote.PlaySound:FireServer(sp.Handle.Equip)
	Load(c.Humanoid)
	Play("Hold")
	if mouse==nil then
		print("Mouse not found")
		return 
	end
	mouse.Icon=Cursors[1]
	mouse.KeyDown:connect(function(key) onKeyDown(key,mouse) end)
	mouse.Button1Down:connect(function() onButton1Down(mouse) end)
	mouse.Button1Up:connect(function() onButton1Up(mouse) end)
	
	local mobilebutton = ContextActionService:BindAction("ReloadButton",onButtonPress,true,"R")
	ContextActionService:SetPosition("ReloadButton",UDim2.new(0.81,-25,-0.142,25))
	ContextActionService:SetImage("ReloadButton","http://www.roblox.come/asset/?id=1398003510")
	
	equiped=true
	if #Cursors>1 then
		while equiped do
			t=r.Stepped:wait()
			local action=sp.Parent:FindFirstChild("Pose")
			if action~=nil then
				if sp.Parent.Pose.Value=="Standing" then
					Spread=MinSpread
				else
					Spread=MinSpread+((4/10)*(MaxSpread-MinSpread))
				end
			else
				Spread=MinSpread
			end
			if t-last<SpreadRate then
				Spread=Spread+.1*(MaxSpread-MinSpread)
			end
			if t-last2<SpreadRate then
				Spread=Spread+.1*(MaxSpread-MinSpread)
			end
			if t-last3<SpreadRate then
				Spread=Spread+.1*(MaxSpread-MinSpread)
			end
			if t-last4<SpreadRate then
				Spread=Spread+.1*(MaxSpread-MinSpread)
			end
			if t-last5<SpreadRate then
				Spread=Spread+.1*(MaxSpread-MinSpread)
			end
			if t-last6<SpreadRate then
				Spread=Spread+.1*(MaxSpread-MinSpread)
			end
			if not reloading then
				local percent=(Spread-MinSpread)/(MaxSpread-MinSpread)
				for i=0,#Cursors-1 do
					if percent>(i/(#Cursors-1))-((1/(#Cursors-1))/2) and percent<(i/(#Cursors-1))+((1/(#Cursors-1))/2) then
						mouse.Icon=Cursors[i+1]
					end
				end
			end
			wait(Firerate*.9)
		end
	end
end

local function onUnequippedLocal(mouse)
	local mobilebutton = ContextActionService:BindAction("ReloadButton",onButtonPress,false,"R")
	ContextActionService:SetPosition("ReloadButton",UDim2.new(0.81,-25,-0.142,25))
	ContextActionService:SetImage("ReloadButton","http://www.roblox.come/asset/?id=1398003510")
	Stop("Fire")
	for i,v in pairs(Ans) do
		Stop(i)
		
	end
	if ObjectLocalTransparencyModifier then
		ObjectLocalTransparencyModifier:disconnect()
	end
	local camera = game.Workspace.CurrentCamera
	if (camera.focus.p - camera.CoordinateFrame.p).magnitude <= 1 then
		for i, v in pairs(LocalObjects) do
			if v.Object then
				v.Object.LocalTransparencyModifier = 1
			end
		end
	end
	LocalObjects = {}
	
	equiped=false
	reloading=false
end
sp.Equipped:connect(onEquippedLocal)
sp.Unequipped:connect(onUnequippedLocal)
local UserInputService = game:GetService("UserInputService")
local ContextActionService = game:GetService("ContextActionService")

-- function to handle firing the gun
local function FireGun()
  -- insert code here to create a bullet or projectile and fire it
end

-- function to handle when the player presses the left mouse button
local function OnInput(actionName, inputState, inputObject)
  if inputState == Enum.UserInputState.Begin then
    FireGun()
  end
end

-- bind the OnInput function to the left mouse button
ContextActionService:BindAction("FireGun", OnInput, false, Enum.UserInputType.MouseButton1)

In the FireGun function, you can insert code to create a bullet or projectile and fire it. You can use a Raycast or other method to determine where the bullet should go and what it should hit.

Test the gun in Roblox Studio to make sure it fires correctly when the player presses the left mouse button.

1 Like

Thanks, this is working fine :+1:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.