--Set up input changed class for controllers.

local ControllerDown = false
table.insert(EventsToDisconnect,UserInputService.InputChanged:Connect(function(Input,Processed)
	if Processed then return end
	local Character = Player.Character
	if not Character then return end
	local Humanoid = Character:FindFirstChildOfClass("Humanoid")
	if not Humanoid or Humanoid.Health <= 0 then return end
	
	--Disconnect the event if the tool is unparented.
	DisconnectEvents()
	
	--Handle input if it is the right trigger.
	if (Input.UserInputType == Enum.UserInputType.Gamepad1 or Input.UserInputType == Enum.UserInputType.Gamepad2) and Input.KeyCode == Enum.KeyCode.ButtonR2 then
		local ShouldBeDown = (Input.Position.Z > 0.8)
		
		if ShouldBeDown and not ControllerDown then
			--If it is 80% down and it was up, set it down.
			ControllerDown = true
			
			if VRService.VREnabled then
				--The camera's CFrame is used with VR.
				--For a VR version, a more robust implemention should be done.
				local CameraCF = Camera.CFrame
				local Position = CastRay(CameraCF.p,CameraCF.lookVector,1000)
				LongInputBeganEvent:Fire(Position)
				InputBeganEvent:Fire(Position)
			else
				--The center mouse is used with controllers.
				local Position = Get3DPosition(Mouse.X,Mouse.Y)
				LongInputBeganEvent:Fire(Position)
				InputBeganEvent:Fire(Position)
			end
		elseif not ShouldBeDown and ControllerDown then
			--If it is not 80% down and it was down, set it to up.
			ControllerDown = false
			
			if VRService.VREnabled then
				--The camera's CFrame is used with VR.
				--For a VR version, a more robust implemention should be done.
				local CameraCF = Camera.CFrame
				InputEndedEvent:Fire(CastRay(CameraCF.p,CameraCF.lookVector,1000))
			else
				--The center mouse is used with controllers.
				InputEndedEvent:Fire(Get3DPosition(Mouse.X,Mouse.Y))
			end
		end
	end
end))
