local function Z(Z)local h=math.min(Utility.ViewSizeY()*.33,250)local S=h return Z.X<=S and Z.Y>Utility.ViewSizeY()-h end local function h(Z)local h=math.min(Utility.ViewSizeY()*.33,250)local S=h return Z.X>=Utility.ViewSizeX()-S and Z.Y>Utility.ViewSizeY()-h end local function S(Z)local h=findPlayerHumanoid(Player)return h~=nil and h.Health>0 end local function j(Z)if Z~=nil then for Z,h in pairs(Z:GetChildren())do if h:IsA("\084\111\111\108")then return h end end end end local function y(Z,h)local S=40 local j={}do local Z=h for h=0,15,1 do table.insert(j,CFrame.Angles(0,(math.pi/8)*h,0)*Z)end end local y={}local function f()for Z,j in pairs(y)do local y=-1*h local f=(y:Dot(j.Vector)+1)/2 local V=j.Distance/S j.Value=f*V end end for h,j in pairs(j)do local f,V=Utility.Raycast(Ray.new(Z,j*S),true,{Player.Character})if V then table.insert(y,{Vector=j,Distance=(V-Z).magnitude})else table.insert(y,{Vector=j;Distance=S})end end f()table.sort(y,function(Z,h)return Z.Value>h.Value end)return y end local f=1 local V=nil local R=nil local M=nil local d=nil local function t()DrivingTo=nil if V then V:Cancel()end if M then M:disconnect()M=nil end if d then d:disconnect()d=nil end if R then DebrisService:AddItem(R,0)R=nil end end local function H(Z)local h=Z[1].Position.X local S=Z[1].Position.Y local j=Z[1].Position.Z local y=Z[1].Position.X local f=Z[1].Position.Y local V=Z[1].Position.Z for R=2,#Z,1 do h=math_max(h,Z[R].Position.X)S=math_max(S,Z[R].Position.Y)j=math_max(j,Z[R].Position.Z)y=math_min(y,Z[R].Position.X)f=math_min(f,Z[R].Position.Y)V=math_min(V,Z[R].Position.Z)end return Region3.new(Vector3_new(y,f,V),Vector3_new(h,S,j))end local function o(Z,h)if h.X<Z.CFrame.p.X-Z.Size.X/2 or h.X>Z.CFrame.p.X+Z.Size.X/2 then return false end if h.Z<Z.CFrame.p.Z-Z.Size.Z/2 or h.Z>Z.CFrame.p.Z+Z.Size.Z/2 then return false end return true end local C=nil local w=0 local q=0 local function E(Z,h)f=f+1 local Q=f local a=workspace.CurrentCamera local u=Player.Character if not S(u)then return end if#Z==1 or h then if a then local S=Utility.GetUnitRay(Z[1].x,Z[1].y,MyMouse.ViewSizeX,MyMouse.ViewSizeY,a)local f=Ray.new(S.Origin,S.Direction*400)local Q,F=Utility.Raycast(f,true,{u})local T,r=Utility.FindChacterAncestor(Q)local P=u and(u:FindFirstChild("\072\117\109\097\110\111\105\100")and(u:FindFirstChild("\072\117\109\097\110\111\105\100")).Torso)local J=P.CFrame.p if h then F=h T=nil end if T and(r and(r.Torso and(r.Torso.CFrame.p-P.CFrame.p).magnitude<7))then t()local Z=findPlayerHumanoid(Player)if Z then Z:MoveTo(F)end w=w+1 local h=w local S=j(u)if S then S:Activate()LastFired=tick()end elseif F and(u and not CurrentSeatPart)then local Z=Pather(u,F)if Z:IsValidPath()then q=0 Player:Move(Vector3_new(1,0,0))Player:Move(ZERO_VECTOR3)Z:Start()if BindableEvent_OnFailStateChanged then BindableEvent_OnFailStateChanged:Fire(false)end t()local h=CreateDestinationIndicator(F)h.Parent=a V=Z R=h if C then C:Run()end M=Z.Finished:connect(function()if C then C:Stop()end if h then if R==h then R=nil end DebrisService:AddItem(h,0)h=nil end if T then local Z=findPlayerHumanoid(Player)w=w+1 local h=w local S=j(u)if S then S:Activate()LastFired=tick()end if Z then Z:MoveTo(F)end end local Z=P and P.CFrame.p if Z and(J and tick()-Utility.GetLastInput()>2)then local h=y(Z,((J-Z)*XZ_VECTOR3).unit)if h[1]and(h[1].Vector and(h[1].Vector.magnitude>=.5 and h[1].Distance>3))then if CameraModule then local S=CameraModule:LookAtPreserveHeight(Z+h[1].Vector*h[1].Distance)local j,y=CameraModule:TweenCameraLook(S)end end end end)d=Z.PathFailed:connect(function()if C then C:Stop()end if h then FlashRed(h)DebrisService:AddItem(h,3)end end)else if F then local Z=CreateDestinationIndicator(F)FlashRed(Z)DebrisService:AddItem(Z,1)Z.Parent=a if R==nil then q=q+1 if q>=3 then if BindableEvent_OnFailStateChanged then BindableEvent_OnFailStateChanged:Fire(true)end t()end end end end elseif F and(u and CurrentSeatPart)then local h=CreateDestinationIndicator(F)h.Parent=a R=h DrivingTo=F local S=CurrentSeatPart:GetConnectedParts(true)while wait()do if CurrentSeatPart and R==h then local Z=H(S)if o(Z,h.Position)then DebrisService:AddItem(h,0)h=nil DrivingTo=nil break end else DebrisService:AddItem(h,0)if CurrentSeatPart==nil and h==R then DrivingTo=nil E(Z,F)end h=nil break end end else end end elseif#Z>=2 then if a then w=w+1 local h=w local S=Utility.AveragePoints(Z)local y=Utility.GetUnitRay(S.x,S.y,MyMouse.ViewSizeX,MyMouse.ViewSizeY,a)local f=j(u)if f then f:Activate()LastFired=tick()end end end end local function Q()local S={}local j=0 local y=Enum.HumanoidStateType.Running local f={}local V=0 local M=tick()local d=Vector2.new()local H=tick()local o=Vector2.new()local w=tick()local q={[Enum.KeyCode.W]=true,[Enum.KeyCode.A]=true;[Enum.KeyCode.S]=true,[Enum.KeyCode.D]=true;[Enum.KeyCode.Up]=true,[Enum.KeyCode.Down]=true}local Q=nil local a=nil local u=nil local F=nil local T=nil local r=nil local P=nil local J=nil local e=nil local A=nil local function b(Z)if Z then Z:disconnect()end end local function L()b(Q)b(a)b(u)b(F)b(T)b(r)b(P)b(e)b(J)pcall(function()RunService:UnbindFromRenderStep("\067\108\105\099\107\084\111\077\111\118\101\082\101\110\100\101\114\085\112\100\097\116\101")end)b(A)end local function i(Z)return Z==Z and(Z~=1/0 and Z~=-1/0)end local function g(Z,h)return math_atan2(h.X*Z.Z-h.Z*Z.X,h.X*Z.X+h.Z*Z.Z)end CameraModule=ClassicCameraModule()do function CameraModule.LookAtPreserveHeight(h,Z)local S=workspace.CurrentCamera local j=S.Focus.p local y=CameraModule.cframe local f=(Vector3_new(y.lookVector.x,0,y.lookVector.z)).magnitude local V=(Vector3_new(Z.x,j.y,Z.z)-j).unit*f local R=V+Vector3_new(0,y.lookVector.y,0)local M=(j-y.p).magnitude local d=j-R.unit*M return CFrame.new(d,d+R)end local Z=(CFrame.new()).lerp function CameraModule.TweenCameraLook(j,h,S)local y=2.718281828459 local function f(Z)return 1/(1+y^(-Z*1.5))end local function V(Z,h,S,j)if Z>=j then return h+S end return S*math_sin((Z/j)*(math_pi/2))+h end local R,M=CFrame_new(ZERO_VECTOR3,j:GetCameraLook()),h-h.p local d=GetThetaBetweenCFrames(R,M)d=clamp(0,math_pi,d)local t=.65*f(d-math_pi/4)+.15 if S then t=d/S end local H=tick()local o=H+t j.UpdateTweenFunction=function()local h=tick()-H local S=clamp(0,1,V(h,0,1,t))local y=Z(R,M,S)local f=g(y.lookVector,j:GetCameraLook())if i(f)and math_abs(f)>.0001 then j.RotateInput=j.RotateInput+Vector2_new(f,0)end return h>=o or S>=1 end end end local function N(Z,h)if f[Z]==nil and not h then V=V+1 end f[Z]=h end local function x(Z,h)if f[Z]==nil then f[Z]=h if not h then V=V+1 end end end local function k(Z,h)if f[Z]~=nil and f[Z]==false then V=V-1 end f[Z]=nil end local function X(S)L()a=UIS.InputBegan:connect(function(S,j)if S.UserInputType==Enum.UserInputType.Touch then N(S,j)local y=Z(S.Position)local V=h(S.Position)if V or y then for j,f in pairs(f)do if j~=S then local S=Z(j.Position)local f=h(j.Position)if j.UserInputState~=Enum.UserInputState.End and(y and f or V and S)then if BindableEvent_OnFailStateChanged then BindableEvent_OnFailStateChanged:Fire(true)end return end end end end end if j==false and(S.UserInputType==Enum.UserInputType.Keyboard and q[S.KeyCode])then t()end if S.UserInputType==Enum.UserInputType.MouseButton1 then M=tick()d=S.Position end if S.UserInputType==Enum.UserInputType.MouseButton2 then H=tick()o=S.Position end end)u=UIS.InputChanged:connect(function(Z,h)if Z.UserInputType==Enum.UserInputType.Touch then x(Z,h)end end)F=UIS.InputEnded:connect(function(Z,h)if Z.UserInputType==Enum.UserInputType.Touch then k(Z,h)end if Z.UserInputType==Enum.UserInputType.MouseButton2 then w=tick()local h=Z.Position if w-H<.25 and(h-o).magnitude<5 then local Z={h}E(Z)end end end)Q=UIS.TouchTap:connect(function(Z,h)if not h then E(Z)end end)if not UIS.TouchEnabled then if C then C:Stop()C=nil end C=AutoJumper()end local function j(Z,h)local S=h-Z.Position S=(Vector3_new(S.X,0,S.Z)).unit local j=(Vector3_new(Z.CFrame.lookVector.X,0,Z.CFrame.lookVector.Z)).unit local y=S-j local f=y.magnitude local V=math_deg(math_acos(S:Dot(j)))local R=(Z.CFrame:pointToObjectSpace(h)).X>0 local M=0 if f<.25 then M=1 end if f>1.8 then M=-1 end local d=CurrentSeatPart.Position-DrivingTo local t=CurrentSeatPart.Velocity if t.magnitude*1.5>d.magnitude then if t.magnitude*.5>d.magnitude then M=-M else M=0 end end local H=0 if V>5 and V<175 then if R then H=1 else H=-1 end end local o=math_deg(CurrentSeatPart.RotVelocity.magnitude)local C=math_max(math_min(V,180-V),10)if(CurrentSeatPart.RotVelocity.X<0)==(H<0)then if o*1.5>C then if o*.5>C then H=-H else H=0 end end end return M,H end local function y()if CameraModule then if CameraModule.UserPanningTheCamera then CameraModule.UpdateTweenFunction=nil else if CameraModule.UpdateTweenFunction then local Z=CameraModule.UpdateTweenFunction()if Z then CameraModule.UpdateTweenFunction=nil end end end CameraModule:Update()end if CurrentSeatPart then if DrivingTo then local Z,h=j(CurrentSeatPart,DrivingTo)CurrentSeatPart.Throttle=Z CurrentSeatPart.Steer=h end end end local V=pcall(function()RunService:BindToRenderStep("\067\108\105\099\107\084\111\077\111\118\101\082\101\110\100\101\114\085\112\100\097\116\101",Enum.RenderPriority.Camera.Value-1,y)end)if not V then if e then e:disconnect()end e=RunService.RenderStepped:connect(y)end local P=false local i=false local function g(Z,h,S)if h then if BindableEvent_EnableTouchJump then BindableEvent_EnableTouchJump:Fire(true)end if S and S.ClassName=="\086\101\104\105\099\108\101\083\101\097\116"then CurrentSeatPart=S if C then C:Stop()C=nil P=true else P=false end if Z.AutoJumpEnabled then i=true Z.AutoJumpEnabled=false end end else CurrentSeatPart=nil if BindableEvent_EnableTouchJump then BindableEvent_EnableTouchJump:Fire(false)end if P then C=AutoJumper()P=false end if i then Z.AutoJumpEnabled=true i=false end end end local function X(Z)if UIS.TouchEnabled then if Z:IsA("\084\111\111\108")then Z.ManualActivationOnly=true end end if Z:IsA("\072\117\109\097\110\111\105\100")then b(T)T=Z.Died:connect(function()DebrisService:AddItem(R,1)if C then C:Stop()C=nil end end)local h=false local S=false A=Z.Seated:connect(function(h,S)g(Z,h,S)end)if Z.SeatPart then g(Z,true,Z.SeatPart)end end end r=S.ChildAdded:connect(function(Z)X(Z)end)J=S.ChildRemoved:connect(function(Z)if UIS.TouchEnabled then if Z:IsA("\084\111\111\108")then Z.ManualActivationOnly=false end end end)for Z,h in pairs(S:GetChildren())do X(h)end end local G=false function S.Stop(Z)if G then L()t()if C then C:Stop()C=nil end if CameraModule then CameraModule.UpdateTweenFunction=nil CameraModule:SetEnabled(false)end if UIS.TouchEnabled then local Z=Player.Character if Z then for Z,h in pairs(Z:GetChildren())do if h:IsA("\084\111\111\108")then h.ManualActivationOnly=false end end end end DrivingTo=nil G=false end end function S.Start(Z)if not G then if Player.Character then X(Player.Character)end P=Player.CharacterAdded:connect(X)if CameraModule then CameraModule:SetEnabled(true)end G=true end end return S end return Q

local function IsInBottomLeft(pt)
	local joystickHeight = math.min(Utility.ViewSizeY() * 0.33, 250)
	local joystickWidth = joystickHeight
	return pt.X <= joystickWidth and pt.Y > Utility.ViewSizeY() - joystickHeight
end

local function IsInBottomRight(pt)
	local joystickHeight = math.min(Utility.ViewSizeY() * 0.33, 250)
	local joystickWidth = joystickHeight
	return pt.X >= Utility.ViewSizeX() - joystickWidth and pt.Y > Utility.ViewSizeY() - joystickHeight
end

local function CheckAlive(character)
	local humanoid = findPlayerHumanoid(Player)
	return humanoid ~= nil and humanoid.Health > 0
end

local function GetEquippedTool(character)
	if character ~= nil then
		for _, child in pairs(character:GetChildren()) do
			if child:IsA('Tool') then
				return child
			end
		end
	end
end

local function ExploreWithRayCast(currentPoint, originDirection)
	local TestDistance = 40
	local TestVectors = {}
	do
		local forwardVector = originDirection;
		for i = 0, 15 do
			table.insert(TestVectors, CFrame.Angles(0, math.pi / 8 * i, 0) * forwardVector)
		end
	end

	local testResults = {}
	-- Heuristic should be something along the lines of distance and closeness to the traveling direction
	local function ExploreHeuristic()
		for _, testData in pairs(testResults) do
			local walkDirection = -1 * originDirection
			local directionCoeff = (walkDirection:Dot(testData['Vector']) + 1) / 2
			local distanceCoeff = testData['Distance'] / TestDistance
			testData["Value"] = directionCoeff * distanceCoeff
		end
	end

	for i, vec in pairs(TestVectors) do
		local hitPart, hitPos = Utility.Raycast(Ray.new(currentPoint, vec * TestDistance), true, {Player.Character})
		if hitPos then
			table.insert(testResults, {Vector = vec; Distance = (hitPos - currentPoint).magnitude})
		else
			table.insert(testResults, {Vector = vec; Distance = TestDistance})
		end
	end

	ExploreHeuristic()

	table.sort(testResults, function(a,b) return a["Value"] > b["Value"] end)

	return testResults
end

local TapId = 1
local ExistingPather = nil
local ExistingIndicator = nil
local PathCompleteListener = nil
local PathFailedListener = nil

local function CleanupPath()
	DrivingTo = nil
	if ExistingPather then
		ExistingPather:Cancel()
	end
	if PathCompleteListener then
		PathCompleteListener:disconnect()
		PathCompleteListener = nil
	end
	if PathFailedListener then
		PathFailedListener:disconnect()
		PathFailedListener = nil
	end
	if ExistingIndicator then
		DebrisService:AddItem(ExistingIndicator, 0)
		ExistingIndicator = nil
	end
end

local function getExtentsSize(Parts)
	local maxX = Parts[1].Position.X
	local maxY = Parts[1].Position.Y
	local maxZ = Parts[1].Position.Z
	local minX = Parts[1].Position.X
	local minY = Parts[1].Position.Y
	local minZ = Parts[1].Position.Z
	for i = 2, #Parts do
		maxX = math_max(maxX, Parts[i].Position.X)
		maxY = math_max(maxY, Parts[i].Position.Y)
		maxZ = math_max(maxZ, Parts[i].Position.Z)
		minX = math_min(minX, Parts[i].Position.X)
		minY = math_min(minY, Parts[i].Position.Y)
		minZ = math_min(minZ, Parts[i].Position.Z)
	end
	return Region3.new(Vector3_new(minX, minY, minZ), Vector3_new(maxX, maxY, maxZ))
end

local function inExtents(Extents, Position)
	if Position.X < (Extents.CFrame.p.X - Extents.Size.X/2) or Position.X > (Extents.CFrame.p.X + Extents.Size.X/2) then
		return false
	end
	if Position.Z < (Extents.CFrame.p.Z - Extents.Size.Z/2) or Position.Z > (Extents.CFrame.p.Z + Extents.Size.Z/2) then
		return false
	end
	--ignoring Y for now
	return true
end

local AutoJumperInstance = nil
local ShootCount = 0
local FailCount = 0
local function OnTap(tapPositions, goToPoint)
	-- Good to remember if this is the latest tap event
	TapId = TapId + 1
	local thisTapId = TapId


	local camera = workspace.CurrentCamera
	local character = Player.Character


	if not CheckAlive(character) then return end

	-- This is a path tap position
	if #tapPositions == 1 or goToPoint then
		if camera then
			local unitRay = Utility.GetUnitRay(tapPositions[1].x, tapPositions[1].y, MyMouse.ViewSizeX, MyMouse.ViewSizeY, camera)
			local ray = Ray.new(unitRay.Origin, unitRay.Direction*400)
			local hitPart, hitPt = Utility.Raycast(ray, true, {character})

			local hitChar, hitHumanoid = Utility.FindChacterAncestor(hitPart)
			local torso = character and character:FindFirstChild("Humanoid") and character:FindFirstChild("Humanoid").Torso
			local startPos = torso.CFrame.p
			if goToPoint then
				hitPt = goToPoint
				hitChar = nil
			end
			if hitChar and hitHumanoid and hitHumanoid.Torso and (hitHumanoid.Torso.CFrame.p - torso.CFrame.p).magnitude < 7 then
				CleanupPath()

				local myHumanoid = findPlayerHumanoid(Player)
				if myHumanoid then
					myHumanoid:MoveTo(hitPt)
				end

				ShootCount = ShootCount + 1
				local thisShoot = ShootCount
				-- Do shooot
				local currentWeapon = GetEquippedTool(character)
				if currentWeapon then
					currentWeapon:Activate()
					LastFired = tick()
				end
			elseif hitPt and character and not CurrentSeatPart then
				local thisPather = Pather(character, hitPt)
				if thisPather:IsValidPath() then
					FailCount = 0
					-- TODO: Remove when bug in engine is fixed
					Player:Move(Vector3_new(1, 0, 0))
					Player:Move(ZERO_VECTOR3)
					thisPather:Start()
					if BindableEvent_OnFailStateChanged then
						BindableEvent_OnFailStateChanged:Fire(false)
					end
					CleanupPath()

					local destinationGlobe = CreateDestinationIndicator(hitPt)
					destinationGlobe.Parent = camera

					ExistingPather = thisPather
					ExistingIndicator = destinationGlobe

					if AutoJumperInstance then
						AutoJumperInstance:Run()
					end

					PathCompleteListener = thisPather.Finished:connect(function()
						if AutoJumperInstance then
							AutoJumperInstance:Stop()
						end
						if destinationGlobe then
							if ExistingIndicator == destinationGlobe then
								ExistingIndicator = nil
							end
							DebrisService:AddItem(destinationGlobe, 0)
							destinationGlobe = nil
						end
						if hitChar then
							local humanoid = findPlayerHumanoid(Player)
							ShootCount = ShootCount + 1
							local thisShoot = ShootCount
							-- Do shoot
							local currentWeapon = GetEquippedTool(character)
							if currentWeapon then
								currentWeapon:Activate()
								LastFired = tick()
							end
							if humanoid then
								humanoid:MoveTo(hitPt)
							end
						end
						local finishPos = torso and torso.CFrame.p --hitPt
						if finishPos and startPos and tick() - Utility.GetLastInput() > 2 then
							local exploreResults = ExploreWithRayCast(finishPos, ((startPos - finishPos) * XZ_VECTOR3).unit)
							-- Check for Nans etc..
							if exploreResults[1] and exploreResults[1]["Vector"] and exploreResults[1]["Vector"].magnitude >= 0.5 and exploreResults[1]["Distance"] > 3 then
								if CameraModule then
									local rotatedCFrame = CameraModule:LookAtPreserveHeight(finishPos + exploreResults[1]["Vector"] * exploreResults[1]["Distance"])
									local finishedSignal, duration = CameraModule:TweenCameraLook(rotatedCFrame)
								end
							end
						end
					end)
					PathFailedListener = thisPather.PathFailed:connect(function()
						if AutoJumperInstance then
							AutoJumperInstance:Stop()
						end
						if destinationGlobe then
							FlashRed(destinationGlobe)
							DebrisService:AddItem(destinationGlobe, 3)
						end
					end)
				else
					if hitPt then
						-- Feedback here for when we don't have a good path
						local failedGlobe = CreateDestinationIndicator(hitPt)
						FlashRed(failedGlobe)
						DebrisService:AddItem(failedGlobe, 1)
						failedGlobe.Parent = camera
						if ExistingIndicator == nil then
							FailCount = FailCount + 1
							if FailCount >= 3 then
								if BindableEvent_OnFailStateChanged then
									BindableEvent_OnFailStateChanged:Fire(true)
								end
								CleanupPath()
							end
						end
					end
				end
			elseif hitPt and character and CurrentSeatPart then 
				local destinationGlobe = CreateDestinationIndicator(hitPt)
				destinationGlobe.Parent = camera
				ExistingIndicator = destinationGlobe
				DrivingTo = hitPt		
				local ConnectedParts = CurrentSeatPart:GetConnectedParts(true)
				
				while wait() do
					if CurrentSeatPart and ExistingIndicator == destinationGlobe then
						local ExtentsSize = getExtentsSize(ConnectedParts)
						if inExtents(ExtentsSize, destinationGlobe.Position) then
							DebrisService:AddItem(destinationGlobe, 0)
							destinationGlobe = nil
							DrivingTo = nil
							break
						end
					else
						DebrisService:AddItem(destinationGlobe, 0)
						if CurrentSeatPart == nil and destinationGlobe == ExistingIndicator then
							DrivingTo = nil
							OnTap(tapPositions, hitPt)
						end
						destinationGlobe = nil
						break
					end
				end		
				
			else
				-- no hit pt
			end
		end
	elseif #tapPositions >= 2 then
		if camera then
			ShootCount = ShootCount + 1
			local thisShoot = ShootCount
			-- Do shoot
			local avgPoint = Utility.AveragePoints(tapPositions)
			local unitRay = Utility.GetUnitRay(avgPoint.x, avgPoint.y, MyMouse.ViewSizeX, MyMouse.ViewSizeY, camera)
			local currentWeapon = GetEquippedTool(character)
			if currentWeapon then
				currentWeapon:Activate()
				LastFired = tick()
			end
		end
	end
end


local function CreateClickToMoveModule()
	local this = {}

	local LastStateChange = 0
	local LastState = Enum.HumanoidStateType.Running
	local FingerTouches = {}
	local NumUnsunkTouches = 0
	-- PC simulation
	local mouse1Down = tick()
	local mouse1DownPos = Vector2.new()
	local mouse2Down = tick()
	local mouse2DownPos = Vector2.new()
	local mouse2Up = tick()

	local movementKeys = {
		[Enum.KeyCode.W] = true;
		[Enum.KeyCode.A] = true;
		[Enum.KeyCode.S] = true;
		[Enum.KeyCode.D] = true;
		[Enum.KeyCode.Up] = true;
		[Enum.KeyCode.Down] = true;
	}

	local TapConn = nil
	local InputBeganConn = nil
	local InputChangedConn = nil
	local InputEndedConn = nil
	local HumanoidDiedConn = nil
	local CharacterChildAddedConn = nil
	local OnCharacterAddedConn = nil
	local CharacterChildRemovedConn = nil
	local RenderSteppedConn = nil
	local HumanoidSeatedConn = nil

	local function disconnectEvent(event)
		if event then
			event:disconnect()
		end
	end

	local function DisconnectEvents()
		disconnectEvent(TapConn)
		disconnectEvent(InputBeganConn)
		disconnectEvent(InputChangedConn)
		disconnectEvent(InputEndedConn)
		disconnectEvent(HumanoidDiedConn)
		disconnectEvent(CharacterChildAddedConn)
		disconnectEvent(OnCharacterAddedConn)
		disconnectEvent(RenderSteppedConn)
		disconnectEvent(CharacterChildRemovedConn)
		pcall(function() RunService:UnbindFromRenderStep("ClickToMoveRenderUpdate") end)
		disconnectEvent(HumanoidSeatedConn)
	end



	local function IsFinite(num)
		return num == num and num ~= 1/0 and num ~= -1/0
	end
	
	local function findAngleBetweenXZVectors(vec2, vec1)
		return math_atan2(vec1.X*vec2.Z-vec1.Z*vec2.X, vec1.X*vec2.X + vec1.Z*vec2.Z)
	end
	
	-- Setup the camera
	CameraModule = ClassicCameraModule()

	do
		-- Extend The Camera Module Class
		function CameraModule:LookAtPreserveHeight(newLookAtPt)
			local camera = 	workspace.CurrentCamera

			local focus = camera.Focus.p

			local cameraCFrame = CameraModule.cframe
			local mag = Vector3_new(cameraCFrame.lookVector.x, 0, cameraCFrame.lookVector.z).magnitude
			local newLook = (Vector3_new(newLookAtPt.x, focus.y, newLookAtPt.z) - focus).unit * mag
			local flippedLook = newLook + Vector3_new(0, cameraCFrame.lookVector.y, 0)

			local distance = (focus - cameraCFrame.p).magnitude

			local newCamPos = focus - flippedLook.unit * distance
			return CFrame.new(newCamPos, newCamPos + flippedLook)
		end

		local lerp = CFrame.new().lerp
		function CameraModule:TweenCameraLook(desiredCFrame, speed)
			local e = 2.718281828459
			
			local function SCurve(t)
				return 1/(1 + e^(-t*1.5))
			end

			local function easeOutSine(t, b, c, d)
				if t >= d then return b + c end
				return c * math_sin(t/d * (math_pi/2)) + b;
			end

			local c0, c1 = CFrame_new(ZERO_VECTOR3, self:GetCameraLook()), desiredCFrame - desiredCFrame.p
			local theta = GetThetaBetweenCFrames(c0, c1)
			theta = clamp(0, math_pi, theta)
			local duration = 0.65 * SCurve(theta - math_pi/4) + 0.15
			if speed then
				duration = theta / speed
			end
			local start = tick()
			local finish = start + duration

			self.UpdateTweenFunction = function()
				local currTime = tick() - start
				local alpha = clamp(0, 1, easeOutSine(currTime, 0, 1, duration))
				local newCFrame = lerp(c0, c1, alpha)
				local y = findAngleBetweenXZVectors(newCFrame.lookVector, self:GetCameraLook())
				if IsFinite(y) and math_abs(y) > 0.0001 then
					self.RotateInput = self.RotateInput + Vector2_new(y, 0)
				end
				return (currTime >= finish or alpha >= 1)
			end
		end
	end
	--- Done Extending


	local function OnTouchBegan(input, processed)
		if FingerTouches[input] == nil and not processed then
			NumUnsunkTouches = NumUnsunkTouches + 1
		end
		FingerTouches[input] = processed
	end

	local function OnTouchChanged(input, processed)
		if FingerTouches[input] == nil then
			FingerTouches[input] = processed
			if not processed then
				NumUnsunkTouches = NumUnsunkTouches + 1
			end
		end
	end

	local function OnTouchEnded(input, processed)
			--print("Touch tap fake:" , processed)
			--if not processed then
			--	OnTap({input.Position})
			--end
		if FingerTouches[input] ~= nil and FingerTouches[input] == false then
			NumUnsunkTouches = NumUnsunkTouches - 1
		end
		FingerTouches[input] = nil
	end


	local function OnCharacterAdded(character)
		DisconnectEvents()

		InputBeganConn = UIS.InputBegan:connect(function(input, processed)
			if input.UserInputType == Enum.UserInputType.Touch then
				OnTouchBegan(input, processed)


				-- Give back controls when they tap both sticks
				local wasInBottomLeft = IsInBottomLeft(input.Position)
				local wasInBottomRight = IsInBottomRight(input.Position)
				if wasInBottomRight or wasInBottomLeft then
					for otherInput, _ in pairs(FingerTouches) do
						if otherInput ~= input then
							local otherInputInLeft = IsInBottomLeft(otherInput.Position)
							local otherInputInRight = IsInBottomRight(otherInput.Position)
							if otherInput.UserInputState ~= Enum.UserInputState.End and ((wasInBottomLeft and otherInputInRight) or (wasInBottomRight and otherInputInLeft)) then
								if BindableEvent_OnFailStateChanged then
									BindableEvent_OnFailStateChanged:Fire(true)
								end
								return
							end
						end
					end
				end
			end

			 -- Cancel path when you use the keyboard controls.
			if processed == false and input.UserInputType == Enum.UserInputType.Keyboard and movementKeys[input.KeyCode] then
				CleanupPath()
			end
			if input.UserInputType == Enum.UserInputType.MouseButton1 then
				mouse1Down = tick()
				mouse1DownPos = input.Position
			end
			if input.UserInputType == Enum.UserInputType.MouseButton2 then
				mouse2Down = tick()
				mouse2DownPos = input.Position
			end
		end)

		InputChangedConn = UIS.InputChanged:connect(function(input, processed)
			if input.UserInputType == Enum.UserInputType.Touch then
				OnTouchChanged(input, processed)
			end
		end)

		InputEndedConn = UIS.InputEnded:connect(function(input, processed)
			if input.UserInputType == Enum.UserInputType.Touch then
				OnTouchEnded(input, processed)
			end

			if input.UserInputType == Enum.UserInputType.MouseButton2 then
				mouse2Up = tick()
				local currPos = input.Position
				if mouse2Up - mouse2Down < 0.25 and (currPos - mouse2DownPos).magnitude < 5 then
					local positions = {currPos}
					OnTap(positions)
				end
			end
		end)

		TapConn = UIS.TouchTap:connect(function(touchPositions, processed)
			if not processed then
				OnTap(touchPositions)
			end
		end)

		if not UIS.TouchEnabled then -- PC
			if AutoJumperInstance then
				AutoJumperInstance:Stop()
				AutoJumperInstance = nil
			end
			AutoJumperInstance = AutoJumper()
		end
		
		local function getThrottleAndSteer(object, point)
			local lookVector = (point - object.Position)
			lookVector = Vector3_new(lookVector.X, 0, lookVector.Z).unit
			local objectVector = Vector3_new(object.CFrame.lookVector.X, 0, object.CFrame.lookVector.Z).unit
			local dirVector = lookVector - objectVector
			local mag = dirVector.magnitude
			local degrees = math_deg(math_acos(lookVector:Dot(objectVector)))
			local side = (object.CFrame:pointToObjectSpace(point).X > 0)
			local throttle = 0
			if mag < 0.25 then
				throttle = 1
			end
			if mag > 1.8 then
				throttle = -1
			end
			local distance = CurrentSeatPart.Position - DrivingTo
			local velocity = CurrentSeatPart.Velocity
			if velocity.magnitude*1.5 > distance.magnitude then
				if velocity.magnitude*0.5 > distance.magnitude then
					throttle = -throttle
				else
					throttle = 0
				end
			end
			local steer = 0
			if degrees > 5 and degrees < 175 then
				if side then
					steer = 1
				else
					steer = -1
				end
			end
			local rotatingAt = math_deg(CurrentSeatPart.RotVelocity.magnitude)
			local degreesAway = math_max(math_min(degrees, 180 - degrees), 10)
			if (CurrentSeatPart.RotVelocity.X < 0)== (steer < 0) then
				if rotatingAt*1.5 > degreesAway then
					if rotatingAt*0.5 > degreesAway then
						steer = -steer
					else
						steer = 0
					end
				end
			end
			return throttle, steer
		end
		
		local function Update()
			if CameraModule then
				if CameraModule.UserPanningTheCamera then
					CameraModule.UpdateTweenFunction = nil
				else
					if CameraModule.UpdateTweenFunction then
						local done = CameraModule.UpdateTweenFunction()
						if done then
							CameraModule.UpdateTweenFunction = nil
						end
					end
				end
				CameraModule:Update()
			end

			if CurrentSeatPart then
				if DrivingTo then
					local throttle, steer = getThrottleAndSteer(CurrentSeatPart, DrivingTo)
					CurrentSeatPart.Throttle = throttle
					CurrentSeatPart.Steer = steer
				end
			end
		end
		
		local success = pcall(function() RunService:BindToRenderStep("ClickToMoveRenderUpdate",Enum.RenderPriority.Camera.Value - 1,Update) end)
		if not success then
			if RenderSteppedConn then
				RenderSteppedConn:disconnect()
			end
			RenderSteppedConn = RunService.RenderStepped:connect(Update)
		end
		
		local WasAutoJumper = false
		local WasAutoJumpMobile = false		
		local function onSeated(child, active, currentSeatPart)
			if active then
				if BindableEvent_EnableTouchJump then
					BindableEvent_EnableTouchJump:Fire(true)
				end
				if currentSeatPart and currentSeatPart.ClassName == "VehicleSeat" then
					CurrentSeatPart = currentSeatPart
					if AutoJumperInstance then
						AutoJumperInstance:Stop()
						AutoJumperInstance = nil
						WasAutoJumper = true
					else
						WasAutoJumper = false
					end
					if child.AutoJumpEnabled then
						WasAutoJumpMobile = true
						child.AutoJumpEnabled = false
					end
				end
			else
				CurrentSeatPart = nil
				if BindableEvent_EnableTouchJump then
					BindableEvent_EnableTouchJump:Fire(false)
				end
				if WasAutoJumper then
					AutoJumperInstance = AutoJumper()
					WasAutoJumper = false
				end
				if WasAutoJumpMobile then
					child.AutoJumpEnabled = true
					WasAutoJumpMobile = false
				end
			end
		end

		local function OnCharacterChildAdded(child)
			if UIS.TouchEnabled then
				if child:IsA('Tool') then
					child.ManualActivationOnly = true
				end
			end
			if child:IsA('Humanoid') then
				disconnectEvent(HumanoidDiedConn)
				HumanoidDiedConn = child.Died:connect(function()
					DebrisService:AddItem(ExistingIndicator, 1)
					if AutoJumperInstance then
						AutoJumperInstance:Stop()
						AutoJumperInstance = nil
					end
				end)
				local WasAutoJumper = false
				local WasAutoJumpMobile = false
				HumanoidSeatedConn = child.Seated:connect(function(active, seat) onSeated(child, active, seat) end)
				if child.SeatPart then
					onSeated(child, true, child.SeatPart)
				end
			end
		end

		CharacterChildAddedConn = character.ChildAdded:connect(function(child)
			OnCharacterChildAdded(child)
		end)
		CharacterChildRemovedConn = character.ChildRemoved:connect(function(child)
			if UIS.TouchEnabled then
				if child:IsA('Tool') then
					child.ManualActivationOnly = false
				end
			end
		end)
		for _, child in pairs(character:GetChildren()) do
			OnCharacterChildAdded(child)
		end
	end

	local Running = false

	function this:Stop()
		if Running then
			DisconnectEvents()
			CleanupPath()
			if AutoJumperInstance then
				AutoJumperInstance:Stop()
				AutoJumperInstance = nil
			end
			if CameraModule then
				CameraModule.UpdateTweenFunction = nil
				CameraModule:SetEnabled(false)
			end
			-- Restore tool activation on shutdown
			if UIS.TouchEnabled then
				local character = Player.Character
				if character then
					for _, child in pairs(character:GetChildren()) do
						if child:IsA('Tool') then
							child.ManualActivationOnly = false
						end
					end
				end
			end
			DrivingTo = nil
			Running = false
		end
	end

	function this:Start()
		if not Running then
			if Player.Character then -- retro-listen
				OnCharacterAdded(Player.Character)
			end
			OnCharacterAddedConn = Player.CharacterAdded:connect(OnCharacterAdded)
			if CameraModule then
				CameraModule:SetEnabled(true)
			end
			Running = true
		end
	end

	return this
end

return CreateClickToMoveModule
