This commit is contained in:
lx
2026-07-06 14:01:11 -04:00
commit c4f97d729d
16468 changed files with 935321 additions and 0 deletions
@@ -0,0 +1,320 @@
local RunService = game:GetService('RunService')
local UserInputService = game:GetService('UserInputService')
local PlayersService = game:GetService('Players')
local VRService = game:GetService("VRService")
local StarterPlayer = game:GetService('StarterPlayer')
local RootCamera = script:WaitForChild('RootCamera')
local AttachCamera = require(RootCamera:WaitForChild('AttachCamera'))()
local FixedCamera = require(RootCamera:WaitForChild('FixedCamera'))()
local ScriptableCamera = require(RootCamera:WaitForChild('ScriptableCamera'))()
local TrackCamera = require(RootCamera:WaitForChild('TrackCamera'))()
local WatchCamera = require(RootCamera:WaitForChild('WatchCamera'))()
local OrbitalCamera = require(RootCamera:WaitForChild('OrbitalCamera'))()
local ClassicCamera = require(RootCamera:WaitForChild('ClassicCamera'))()
local FollowCamera = require(RootCamera:WaitForChild('FollowCamera'))()
local PopperCam = require(script:WaitForChild('PopperCam'))
local Invisicam = require(script:WaitForChild('Invisicam'))
local TransparencyController = require(script:WaitForChild('TransparencyController'))()
local VRCamera = require(RootCamera:WaitForChild("VRCamera"))()
local GameSettings = UserSettings().GameSettings
local AllCamerasInLua = false
local success, msg = pcall(function()
AllCamerasInLua = UserSettings():IsUserFeatureEnabled("UserAllCamerasInLua")
end)
if not success then
print("Couldn't get feature UserAllCamerasInLua because:" , msg)
end
local FFlagUserNoCameraClickToMoveSuccess, FFlagUserNoCameraClickToMoveResult = pcall(function() return UserSettings():IsUserFeatureEnabled("UserNoCameraClickToMove") end)
local FFlagUserNoCameraClickToMove = FFlagUserNoCameraClickToMoveSuccess and FFlagUserNoCameraClickToMoveResult
local ClickToMove = FFlagUserNoCameraClickToMove and nil or require(script:WaitForChild('ClickToMove'))()
local isOrbitalCameraEnabled = pcall(function() local test = Enum.CameraType.Orbital end)
-- register what camera scripts we are using
do
local PlayerScripts = PlayersService.LocalPlayer:WaitForChild("PlayerScripts")
local canRegisterCameras = pcall(function() PlayerScripts:RegisterTouchCameraMovementMode(Enum.TouchCameraMovementMode.Default) end)
if canRegisterCameras then
PlayerScripts:RegisterTouchCameraMovementMode(Enum.TouchCameraMovementMode.Follow)
PlayerScripts:RegisterTouchCameraMovementMode(Enum.TouchCameraMovementMode.Classic)
PlayerScripts:RegisterComputerCameraMovementMode(Enum.ComputerCameraMovementMode.Default)
PlayerScripts:RegisterComputerCameraMovementMode(Enum.ComputerCameraMovementMode.Follow)
PlayerScripts:RegisterComputerCameraMovementMode(Enum.ComputerCameraMovementMode.Classic)
end
end
local CameraTypeEnumMap =
{
[Enum.CameraType.Attach] = AttachCamera;
[Enum.CameraType.Fixed] = FixedCamera;
[Enum.CameraType.Scriptable] = ScriptableCamera;
[Enum.CameraType.Track] = TrackCamera;
[Enum.CameraType.Watch] = WatchCamera;
[Enum.CameraType.Follow] = FollowCamera;
}
if isOrbitalCameraEnabled then
CameraTypeEnumMap[Enum.CameraType.Orbital] = OrbitalCamera;
end
local EnabledCamera = nil
local EnabledOcclusion = nil
local cameraSubjectChangedConn = nil
local cameraTypeChangedConn = nil
local renderSteppedConn = nil
local lastInputType = nil
local hasLastInput = false
local function IsTouch()
return UserInputService.TouchEnabled
end
local function shouldUsePlayerScriptsCamera()
local player = PlayersService.LocalPlayer
local currentCamera = workspace.CurrentCamera
if AllCamerasInLua then
return true
else
if player then
if currentCamera == nil or (currentCamera.CameraType == Enum.CameraType.Custom)
or (isOrbitalCameraEnabled and currentCamera.CameraType == Enum.CameraType.Orbital) then
return true
end
end
end
return false
end
local function isClickToMoveOn()
local usePlayerScripts = shouldUsePlayerScriptsCamera()
local player = PlayersService.LocalPlayer
if usePlayerScripts and player then
if (hasLastInput and lastInputType == Enum.UserInputType.Touch) or IsTouch() then -- Touch
if player.DevTouchMovementMode == Enum.DevTouchMovementMode.ClickToMove or
(player.DevTouchMovementMode == Enum.DevTouchMovementMode.UserChoice and GameSettings.TouchMovementMode == Enum.TouchMovementMode.ClickToMove) then
return true
end
else -- Computer
if player.DevComputerMovementMode == Enum.DevComputerMovementMode.ClickToMove or
(player.DevComputerMovementMode == Enum.DevComputerMovementMode.UserChoice and GameSettings.ComputerMovementMode == Enum.ComputerMovementMode.ClickToMove) then
return true
end
end
end
return false
end
local function getCurrentCameraMode()
local usePlayerScripts = shouldUsePlayerScriptsCamera()
local player = PlayersService.LocalPlayer
if usePlayerScripts and player then
if (hasLastInput and lastInputType == Enum.UserInputType.Touch) or IsTouch() then -- Touch (iPad, etc...)
if not FFlagUserNoCameraClickToMove and isClickToMoveOn() then
return Enum.DevTouchMovementMode.ClickToMove.Name
elseif player.DevTouchCameraMode == Enum.DevTouchCameraMovementMode.UserChoice then
local touchMovementMode = GameSettings.TouchCameraMovementMode
if touchMovementMode == Enum.TouchCameraMovementMode.Default then
return Enum.TouchCameraMovementMode.Follow.Name
end
return touchMovementMode.Name
else
return player.DevTouchCameraMode.Name
end
else -- Computer
if not FFlagUserNoCameraClickToMove and isClickToMoveOn() then
return Enum.DevComputerMovementMode.ClickToMove.Name
elseif player.DevComputerCameraMode == Enum.DevComputerCameraMovementMode.UserChoice then
local computerMovementMode = GameSettings.ComputerCameraMovementMode
if computerMovementMode == Enum.ComputerCameraMovementMode.Default then
return Enum.ComputerCameraMovementMode.Classic.Name
end
return computerMovementMode.Name
else
return player.DevComputerCameraMode.Name
end
end
end
end
local function getCameraOcclusionMode()
local usePlayerScripts = shouldUsePlayerScriptsCamera()
local player = PlayersService.LocalPlayer
if usePlayerScripts and player then
return player.DevCameraOcclusionMode
end
end
-- New for AllCameraInLua support
local function shouldUseOcclusionModule()
local player = PlayersService.LocalPlayer
if player and game.Workspace.CurrentCamera and game.Workspace.CurrentCamera.CameraType == Enum.CameraType.Custom then
return true
end
return false
end
local function Update()
if EnabledCamera then
EnabledCamera:Update()
end
if EnabledOcclusion and not VRService.VREnabled then
EnabledOcclusion:Update(EnabledCamera)
end
if shouldUsePlayerScriptsCamera() then
TransparencyController:Update()
end
end
local function SetEnabledCamera(newCamera)
if EnabledCamera ~= newCamera then
if EnabledCamera then
EnabledCamera:SetEnabled(false)
end
EnabledCamera = newCamera
if EnabledCamera then
EnabledCamera:SetEnabled(true)
end
end
end
local function OnCameraMovementModeChange(newCameraMode)
if newCameraMode == Enum.DevComputerMovementMode.ClickToMove.Name then
if FFlagUserNoCameraClickToMove then
--No longer responding to ClickToMove here!
return
end
ClickToMove:Start()
SetEnabledCamera(nil)
TransparencyController:SetEnabled(true)
else
local currentCameraType = workspace.CurrentCamera and workspace.CurrentCamera.CameraType
if VRService.VREnabled and currentCameraType ~= Enum.CameraType.Scriptable then
SetEnabledCamera(VRCamera)
TransparencyController:SetEnabled(false)
elseif (currentCameraType == Enum.CameraType.Custom or not AllCamerasInLua) and newCameraMode == Enum.ComputerCameraMovementMode.Classic.Name then
SetEnabledCamera(ClassicCamera)
TransparencyController:SetEnabled(true)
elseif (currentCameraType == Enum.CameraType.Custom or not AllCamerasInLua) and newCameraMode == Enum.ComputerCameraMovementMode.Follow.Name then
SetEnabledCamera(FollowCamera)
TransparencyController:SetEnabled(true)
elseif (currentCameraType == Enum.CameraType.Custom or not AllCamerasInLua) and (isOrbitalCameraEnabled and (newCameraMode == Enum.ComputerCameraMovementMode.Orbital.Name)) then
SetEnabledCamera(OrbitalCamera)
TransparencyController:SetEnabled(true)
elseif AllCamerasInLua and CameraTypeEnumMap[currentCameraType] then
SetEnabledCamera(CameraTypeEnumMap[currentCameraType])
TransparencyController:SetEnabled(false)
else -- Our camera movement code was disabled by the developer
SetEnabledCamera(nil)
TransparencyController:SetEnabled(false)
end
ClickToMove:Stop()
end
local useOcclusion = shouldUseOcclusionModule()
local newOcclusionMode = getCameraOcclusionMode()
if EnabledOcclusion == Invisicam and (newOcclusionMode ~= Enum.DevCameraOcclusionMode.Invisicam or (not useOcclusion)) then
Invisicam:Cleanup()
end
-- PopperCam does not work with OrbitalCamera, as OrbitalCamera's distance can be fixed.
if useOcclusion then
if newOcclusionMode == Enum.DevCameraOcclusionMode.Zoom and ( isOrbitalCameraEnabled and newCameraMode ~= Enum.ComputerCameraMovementMode.Orbital.Name ) then
EnabledOcclusion = PopperCam
elseif newOcclusionMode == Enum.DevCameraOcclusionMode.Invisicam then
EnabledOcclusion = Invisicam
else
EnabledOcclusion = nil
end
else
EnabledOcclusion = nil
end
end
local function OnCameraTypeChanged(newCameraType)
if newCameraType == Enum.CameraType.Scriptable then
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
end
local function OnCameraSubjectChanged(newSubject)
TransparencyController:SetSubject(newSubject)
end
local function OnNewCamera()
OnCameraMovementModeChange(getCurrentCameraMode())
local currentCamera = workspace.CurrentCamera
if currentCamera then
if cameraSubjectChangedConn then
cameraSubjectChangedConn:disconnect()
end
if cameraTypeChangedConn then
cameraTypeChangedConn:disconnect()
end
cameraSubjectChangedConn = currentCamera:GetPropertyChangedSignal("CameraSubject"):connect(function()
OnCameraSubjectChanged(currentCamera.CameraSubject)
end)
cameraTypeChangedConn = currentCamera:GetPropertyChangedSignal("CameraType"):connect(function()
OnCameraMovementModeChange(getCurrentCameraMode())
OnCameraTypeChanged(currentCamera.CameraType)
end)
OnCameraSubjectChanged(currentCamera.CameraSubject)
OnCameraTypeChanged(currentCamera.CameraType)
end
end
local function OnPlayerAdded(player)
workspace.Changed:connect(function(prop)
if prop == 'CurrentCamera' then
OnNewCamera()
end
end)
player.Changed:connect(function(prop)
OnCameraMovementModeChange(getCurrentCameraMode())
end)
GameSettings.Changed:connect(function(prop)
OnCameraMovementModeChange(getCurrentCameraMode())
end)
RunService:BindToRenderStep("cameraRenderUpdate", Enum.RenderPriority.Camera.Value, Update)
OnNewCamera()
OnCameraMovementModeChange(getCurrentCameraMode())
end
do
while PlayersService.LocalPlayer == nil do PlayersService.PlayerAdded:wait() end
hasLastInput = pcall(function()
lastInputType = UserInputService:GetLastInputType()
UserInputService.LastInputTypeChanged:connect(function(newLastInputType)
lastInputType = newLastInputType
end)
end)
OnPlayerAdded(PlayersService.LocalPlayer)
end
local function OnVREnabled()
OnCameraMovementModeChange(getCurrentCameraMode())
end
VRService:GetPropertyChangedSignal("VREnabled"):connect(OnVREnabled)
@@ -0,0 +1,584 @@
--[[
Invisicam
Modified 5.16.2017 by AllYourBlox to consider combined transparency when looking through multiple parts, and to add
a mode that takes advantage of the reduced cost of ray casts from re-implementing GetPartsObscuringTarget
on the C++ side to be O(N) for N parts hit, rather than O(N^2), and to have optimizations specifically
improving performance of closely bundled rays. Fading is also removed, since it is a frame rate killer with high-poly models,
and on mobile.
Based on Invisicam Version 2.5 by OnlyTwentyCharacters
--]]
local Invisicam = {}
---------------
-- Constants --
---------------
local USE_STACKING_TRANSPARENCY = true -- Multiple items between the subject and camera get transparency values that add up to TARGET_TRANSPARENCY
local TARGET_TRANSPARENCY = 0.75 -- Classic Invisicam's Value, also used by new invisicam for parts hit by head and torso rays
local TARGET_TRANSPARENCY_PERIPHERAL = 0.5 -- Used by new SMART_CIRCLE mode for items not hit by head and torso rays
local MODE = {
CUSTOM = 1, -- Whatever you want!
LIMBS = 2, -- Track limbs
MOVEMENT = 3, -- Track movement
CORNERS = 4, -- Char model corners
CIRCLE1 = 5, -- Circle of casts around character
CIRCLE2 = 6, -- Circle of casts around character, camera relative
LIMBMOVE = 7, -- LIMBS mode + MOVEMENT mode
SMART_CIRCLE = 8, -- More sample points on and around character
CHAR_OUTLINE = 9,
}
Invisicam.MODE = MODE
local STARTING_MODE = MODE.SMART_CIRCLE
local LIMB_TRACKING_SET = {
-- Common to R6, R15
['Head'] = true,
-- R6 Only
['Left Arm'] = true,
['Right Arm'] = true,
['Left Leg'] = true,
['Right Leg'] = true,
-- R15 Only
['LeftLowerArm'] = true,
['RightLowerArm'] = true,
['LeftUpperLeg'] = true,
['RightUpperLeg'] = true
}
local CORNER_FACTORS = {
Vector3.new(1,1,-1),
Vector3.new(1,-1,-1),
Vector3.new(-1,-1,-1),
Vector3.new(-1,1,-1)
}
local CIRCLE_CASTS = 10
local MOVE_CASTS = 3
local SMART_CIRCLE_CASTS = 24
local SMART_CIRCLE_INCREMENT = 2.0 * math.pi / SMART_CIRCLE_CASTS
local CHAR_OUTLINE_CASTS = 24
---------------
-- Variables --
---------------
local RunService = game:GetService('RunService')
local PlayersService = game:GetService('Players')
local Player = PlayersService.LocalPlayer
local Camera = nil
local Character = nil
local HumanoidRootPart = nil
local TorsoPart = nil
local HeadPart = nil
local Mode = nil
local BehaviorFunction = nil
local childAddedConn = nil
local childRemovedConn = nil
local Behaviors = {} -- Map of modes to behavior fns
local SavedHits = {} -- Objects currently being faded in/out
local TrackedLimbs = {} -- Used in limb-tracking casting modes
---------------
--| Utility |--
---------------
local math_min = math.min
local math_max = math.max
local math_cos = math.cos
local math_sin = math.sin
local math_pi = math.pi
local Vector3_new = Vector3.new
local ZERO_VECTOR3 = Vector3_new(0,0,0)
local function AssertTypes(param, ...)
local allowedTypes = {}
local typeString = ''
for _, typeName in pairs({...}) do
allowedTypes[typeName] = true
typeString = typeString .. (typeString == '' and '' or ' or ') .. typeName
end
local theType = type(param)
assert(allowedTypes[theType], typeString .. " type expected, got: " .. theType)
end
-----------------------
--| Local Functions |--
-----------------------
local function LimbBehavior(castPoints)
for limb, _ in pairs(TrackedLimbs) do
castPoints[#castPoints + 1] = limb.Position
end
end
local function MoveBehavior(castPoints)
for i = 1, MOVE_CASTS do
local position, velocity = HumanoidRootPart.Position, HumanoidRootPart.Velocity
local horizontalSpeed = Vector3_new(velocity.X, 0, velocity.Z).Magnitude / 2
local offsetVector = (i - 1) * HumanoidRootPart.CFrame.lookVector * horizontalSpeed
castPoints[#castPoints + 1] = position + offsetVector
end
end
local function CornerBehavior(castPoints)
local cframe = HumanoidRootPart.CFrame
local centerPoint = cframe.p
local rotation = cframe - centerPoint
local halfSize = Character:GetExtentsSize() / 2 --NOTE: Doesn't update w/ limb animations
castPoints[#castPoints + 1] = centerPoint
for i = 1, #CORNER_FACTORS do
castPoints[#castPoints + 1] = centerPoint + (rotation * (halfSize * CORNER_FACTORS[i]))
end
end
local function CircleBehavior(castPoints)
local cframe = nil
if Mode == MODE.CIRCLE1 then
cframe = HumanoidRootPart.CFrame
else
local camCFrame = Camera.CoordinateFrame
cframe = camCFrame - camCFrame.p + HumanoidRootPart.Position
end
castPoints[#castPoints + 1] = cframe.p
for i = 0, CIRCLE_CASTS - 1 do
local angle = (2 * math_pi / CIRCLE_CASTS) * i
local offset = 3 * Vector3_new(math_cos(angle), math_sin(angle), 0)
castPoints[#castPoints + 1] = cframe * offset
end
end
local function LimbMoveBehavior(castPoints)
LimbBehavior(castPoints)
MoveBehavior(castPoints)
end
local function CharacterOutlineBehavior(castPoints)
local torsoUp = TorsoPart.CFrame.upVector.unit
local torsoRight = TorsoPart.CFrame.rightVector.unit
-- Torso cross of points for interior coverage
castPoints[#castPoints + 1] = TorsoPart.CFrame.p
castPoints[#castPoints + 1] = TorsoPart.CFrame.p + torsoUp
castPoints[#castPoints + 1] = TorsoPart.CFrame.p - torsoUp
castPoints[#castPoints + 1] = TorsoPart.CFrame.p + torsoRight
castPoints[#castPoints + 1] = TorsoPart.CFrame.p - torsoRight
if HeadPart then
castPoints[#castPoints + 1] = HeadPart.CFrame.p
end
local cframe = CFrame.new(ZERO_VECTOR3,Vector3_new(Camera.CoordinateFrame.lookVector.X,0,Camera.CoordinateFrame.lookVector.Z))
local centerPoint = (TorsoPart and TorsoPart.Position or HumanoidRootPart.Position)
local partsWhitelist = {TorsoPart}
if HeadPart then
partsWhitelist[#partsWhitelist + 1] = HeadPart
end
for i = 1, CHAR_OUTLINE_CASTS do
local angle = (2 * math_pi * i / CHAR_OUTLINE_CASTS)
local offset = cframe * (3 * Vector3_new(math_cos(angle), math_sin(angle), 0))
offset = Vector3_new(offset.X, math_max(offset.Y, -2.25), offset.Z)
local ray = Ray.new(centerPoint + offset, -3 * offset)
local hit, hitPoint = game.Workspace:FindPartOnRayWithWhitelist(ray, partsWhitelist, false, false)
if hit then
-- Use hit point as the cast point, but nudge it slightly inside the character so that bumping up against
-- walls is less likely to cause a transparency glitch
castPoints[#castPoints + 1] = hitPoint + 0.2 * (centerPoint - hitPoint).unit
end
end
end
-- Helper function for Determinant of 3x3
local function Det3x3(a,b,c,d,e,f,g,h,i)
return (a*(e*i-f*h)-b*(d*i-f*g)+c*(d*h-e*g))
end
-- Smart Circle mode needs the intersection of 2 rays that are known to be in the same plane
-- because they are generated from cross products with a common vector. This function is computing
-- that intersection, but it's actually the general solution for the point halfway between where
-- two skew lines come nearest to each other, which is more forgiving.
local function RayIntersection(p0, v0, p1, v1)
local v2 = v0:Cross(v1)
local d1 = p1.x - p0.x
local d2 = p1.y - p0.y
local d3 = p1.z - p0.z
local denom = Det3x3(v0.x,-v1.x,v2.x,v0.y,-v1.y,v2.y,v0.z,-v1.z,v2.z)
if (denom == 0) then
return ZERO_VECTOR3 -- No solution (rays are parallel)
end
local t0 = Det3x3(d1,-v1.x,v2.x,d2,-v1.y,v2.y,d3,-v1.z,v2.z) / denom
local t1 = Det3x3(v0.x,d1,v2.x,v0.y,d2,v2.y,v0.z,d3,v2.z) / denom
local s0 = p0 + t0 * v0
local s1 = p1 + t1 * v1
local s = s0 + 0.5 * ( s1 - s0 )
-- 0.25 studs is a threshold for deciding if the rays are
-- close enough to be considered intersecting, found through testing
if (s1-s0).Magnitude < 0.25 then
return s
else
return ZERO_VECTOR3
end
end
local function SmartCircleBehavior(castPoints)
local torsoUp = TorsoPart.CFrame.upVector.unit
local torsoRight = TorsoPart.CFrame.rightVector.unit
-- SMART_CIRCLE mode includes rays to head and 5 to the torso.
-- Hands, arms, legs and feet are not included since they
-- are not canCollide and can therefore go inside of parts
castPoints[#castPoints + 1] = TorsoPart.CFrame.p
castPoints[#castPoints + 1] = TorsoPart.CFrame.p + torsoUp
castPoints[#castPoints + 1] = TorsoPart.CFrame.p - torsoUp
castPoints[#castPoints + 1] = TorsoPart.CFrame.p + torsoRight
castPoints[#castPoints + 1] = TorsoPart.CFrame.p - torsoRight
if HeadPart then
castPoints[#castPoints + 1] = HeadPart.CFrame.p
end
local cameraOrientation = Camera.CFrame - Camera.CFrame.p
local torsoPoint = Vector3_new(0,0.5,0) + (TorsoPart and TorsoPart.Position or HumanoidRootPart.Position)
local radius = 2.5
-- This loop first calculates points in a circle of radius 2.5 around the torso of the character, in the
-- plane orthogonal to the camera's lookVector. Each point is then raycast to, to determine if it is within
-- the free space surrounding the player (not inside anything). Two iterations are done to adjust points that
-- are inside parts, to try to move them to valid locations that are still on their camera ray, so that the
-- circle remains circular from the camera's perspective, but does not cast rays into walls or parts that are
-- behind, below or beside the character and not really obstructing view of the character. This minimizes
-- the undesirable situation where the character walks up to an exterior wall and it is made invisible even
-- though it is behind the character.
for i = 1, SMART_CIRCLE_CASTS do
local angle = SMART_CIRCLE_INCREMENT * i - 0.5 * math.pi
local offset = radius * Vector3_new(math_cos(angle), math_sin(angle), 0)
local circlePoint = torsoPoint + cameraOrientation * offset
-- Vector from camera to point on the circle being tested
local vp = circlePoint - Camera.CFrame.p
local ray = Ray.new(torsoPoint, circlePoint - torsoPoint)
local hit, hp, hitNormal = game.Workspace:FindPartOnRayWithIgnoreList(ray, {Character}, false, false )
local castPoint = circlePoint
if hit then
local hprime = hp + 0.1 * hitNormal.unit -- Slightly offset hit point from the hit surface
local v0 = hprime - torsoPoint -- Vector from torso to offset hit point
local d0 = v0.magnitude
local perp = (v0:Cross(vp)).unit
-- Vector from the offset hit point, along the hit surface
local v1 = (perp:Cross(hitNormal)).unit
-- Vector from camera to offset hit
local vprime = (hprime - Camera.CFrame.p).unit
-- This dot product checks to see if the vector along the hit surface would hit the correct
-- side of the invisicam cone, or if it would cross the camera look vector and hit the wrong side
if ( v0.unit:Dot(-v1) < v0.unit:Dot(vprime)) then
castPoint = RayIntersection(hprime, v1, circlePoint, vp)
if castPoint.Magnitude > 0 then
local ray = Ray.new(hprime, castPoint - hprime)
local hit, hitPoint, hitNormal = game.Workspace:FindPartOnRayWithIgnoreList(ray, {Character}, false, false )
if hit then
local hprime2 = hitPoint + 0.1 * hitNormal.unit
castPoint = hprime2
end
else
castPoint = hprime
end
else
castPoint = hprime
end
local ray = Ray.new(torsoPoint, (castPoint - torsoPoint))
local hit, hitPoint, hitNormal = game.Workspace:FindPartOnRayWithIgnoreList(ray, {Character}, false, false )
if hit then
local castPoint2 = hitPoint - 0.1 * (castPoint - torsoPoint).unit
castPoint = castPoint2
end
end
castPoints[#castPoints + 1] = castPoint
end
end
local function CheckTorsoReference()
if Character then
TorsoPart = Character:FindFirstChild("Torso")
if not TorsoPart then
TorsoPart = Character:FindFirstChild("UpperTorso")
if not TorsoPart then
TorsoPart = Character:FindFirstChild("HumanoidRootPart")
end
end
HeadPart = Character:FindFirstChild("Head")
end
end
local function OnCharacterAdded(character)
if childAddedConn then
childAddedConn:disconnect()
childAddedConn = nil
end
if childRemovedConn then
childRemovedConn:disconnect()
childRemovedConn = nil
end
Character = character
TrackedLimbs = {}
local function childAdded(child)
if child:IsA('BasePart') then
if LIMB_TRACKING_SET[child.Name] then
TrackedLimbs[child] = true
end
if (child.Name == 'Torso' or child.Name == 'UpperTorso') then
TorsoPart = child
end
if (child.Name == 'Head') then
HeadPart = child
end
end
end
local function childRemoved(child)
TrackedLimbs[child] = nil
-- If removed/replaced part is 'Torso' or 'UpperTorso' double check that we still have a TorsoPart to use
CheckTorsoReference()
end
childAddedConn = character.ChildAdded:connect(childAdded)
childRemovedConn = character.ChildRemoved:connect(childRemoved)
for _, child in pairs(Character:GetChildren()) do
childAdded(child)
end
end
local function OnCurrentCameraChanged()
local newCamera = workspace.CurrentCamera
if newCamera then
Camera = newCamera
end
end
-----------------------
-- Exposed Functions --
-----------------------
-- Update. Called every frame after the camera movement step
function Invisicam:Update()
-- Bail if there is no Character
if not Character then return end
-- Make sure we still have a HumanoidRootPart
if not HumanoidRootPart then
local humanoid = Character:FindFirstChildOfClass("Humanoid")
if humanoid and humanoid.Torso then
HumanoidRootPart = humanoid.Torso
else
-- Not set up with Humanoid? Try and see if there's one in the Character at all:
HumanoidRootPart = Character:FindFirstChild("HumanoidRootPart")
if not HumanoidRootPart then
-- Bail out, since we're relying on HumanoidRootPart existing
return
end
end
local ancestryChangedConn;
ancestryChangedConn = HumanoidRootPart.AncestryChanged:connect(function(child, parent)
if child == HumanoidRootPart and not parent then
HumanoidRootPart = nil
if ancestryChangedConn and ancestryChangedConn.Connected then
ancestryChangedConn:Disconnect()
ancestryChangedConn = nil
end
end
end)
end
if not TorsoPart then
CheckTorsoReference()
if not TorsoPart then
-- Bail out, since we're relying on Torso existing, should never happen since we fall back to using HumanoidRootPart as torso
return
end
end
-- Make a list of world points to raycast to
local castPoints = {}
BehaviorFunction(castPoints)
-- Cast to get a list of objects between the camera and the cast points
local currentHits = {}
local ignoreList = {Character}
local function add(hit)
currentHits[hit] = true
if not SavedHits[hit] then
SavedHits[hit] = hit.LocalTransparencyModifier
end
end
local hitParts
local hitPartCount = 0
-- Hash table to treat head-ray-hit parts differently than the rest of the hit parts hit by other rays
-- head/torso ray hit parts will be more transparent than peripheral parts when USE_STACKING_TRANSPARENCY is enabled
local headTorsoRayHitParts = {}
local partIsTouchingCamera = {}
local perPartTransparencyHeadTorsoHits = TARGET_TRANSPARENCY
local perPartTransparencyOtherHits = TARGET_TRANSPARENCY
if USE_STACKING_TRANSPARENCY then
-- This first call uses head and torso rays to find out how many parts are stacked up
-- for the purpose of calculating required per-part transparency
local headPoint = HeadPart and HeadPart.CFrame.p or castPoints[1]
local torsoPoint = TorsoPart and TorsoPart.CFrame.p or castPoints[2]
hitParts = Camera:GetPartsObscuringTarget({headPoint, torsoPoint}, ignoreList)
-- Count how many things the sample rays passed through, including decals. This should only
-- count decals facing the camera, but GetPartsObscuringTarget does not return surface normals,
-- so my compromise for now is to just let any decal increase the part count by 1. Only one
-- decal per part will be considered.
for i = 1, #hitParts do
local hitPart = hitParts[i]
hitPartCount = hitPartCount + 1 -- count the part itself
headTorsoRayHitParts[hitPart] = true
for _, child in pairs(hitPart:GetChildren()) do
if child:IsA('Decal') or child:IsA('Texture') then
hitPartCount = hitPartCount + 1 -- count first decal hit, then break
break
end
end
end
if (hitPartCount > 0) then
perPartTransparencyHeadTorsoHits = math.pow( ((0.5 * TARGET_TRANSPARENCY) + (0.5 * TARGET_TRANSPARENCY / hitPartCount)), 1 / hitPartCount )
perPartTransparencyOtherHits = math.pow( ((0.5 * TARGET_TRANSPARENCY_PERIPHERAL) + (0.5 * TARGET_TRANSPARENCY_PERIPHERAL / hitPartCount)), 1 / hitPartCount )
end
end
-- Now get all the parts hit by all the rays
hitParts = Camera:GetPartsObscuringTarget(castPoints, ignoreList)
local partTargetTransparency = {}
-- Include decals and textures
for i = 1, #hitParts do
local hitPart = hitParts[i]
partTargetTransparency[hitPart] =headTorsoRayHitParts[hitPart] and perPartTransparencyHeadTorsoHits or perPartTransparencyOtherHits
-- If the part is not already as transparent or more transparent than what invisicam requires, add it to the list of
-- parts to be modified by invisicam
if hitPart.Transparency < partTargetTransparency[hitPart] then
add(hitPart)
end
-- Check all decals and textures on the part
for _, child in pairs(hitPart:GetChildren()) do
if child:IsA('Decal') or child:IsA('Texture') then
if (child.Transparency < partTargetTransparency[hitPart]) then
partTargetTransparency[child] = partTargetTransparency[hitPart]
add(child)
end
end
end
end
-- Invisibilize objects that are in the way, restore those that aren't anymore
for hitPart, originalLTM in pairs(SavedHits) do
if currentHits[hitPart] then
-- LocalTransparencyModifier gets whatever value is required to print the part's total transparency to equal perPartTransparency
hitPart.LocalTransparencyModifier = (hitPart.Transparency < 1) and ((partTargetTransparency[hitPart] - hitPart.Transparency) / (1.0 - hitPart.Transparency)) or 0
else -- Restore original pre-invisicam value of LTM
hitPart.LocalTransparencyModifier = originalLTM
SavedHits[hitPart] = nil
end
end
end
function Invisicam:SetMode(newMode)
AssertTypes(newMode, 'number')
for modeName, modeNum in pairs(MODE) do
if modeNum == newMode then
Mode = newMode
BehaviorFunction = Behaviors[Mode]
return
end
end
error("Invalid mode number")
end
function Invisicam:SetCustomBehavior(func)
AssertTypes(func, 'function')
Behaviors[MODE.CUSTOM] = func
if Mode == MODE.CUSTOM then
BehaviorFunction = func
end
end
function Invisicam:GetObscuredParts()
return SavedHits
end
-- Want to turn off Invisicam? Be sure to call this after.
function Invisicam:Cleanup()
for hit, originalFade in pairs(SavedHits) do
hit.LocalTransparencyModifier = originalFade
end
end
---------------------
--| Running Logic |--
---------------------
-- Connect to the current and all future cameras
workspace:GetPropertyChangedSignal("CurrentCamera"):connect(OnCurrentCameraChanged)
OnCurrentCameraChanged()
Player.CharacterAdded:connect(OnCharacterAdded)
if Player.Character then
OnCharacterAdded(Player.Character)
end
Behaviors[MODE.CUSTOM] = function() end -- (Does nothing until SetCustomBehavior)
Behaviors[MODE.LIMBS] = LimbBehavior
Behaviors[MODE.MOVEMENT] = MoveBehavior
Behaviors[MODE.CORNERS] = CornerBehavior
Behaviors[MODE.CIRCLE1] = CircleBehavior
Behaviors[MODE.CIRCLE2] = CircleBehavior
Behaviors[MODE.LIMBMOVE] = LimbMoveBehavior
Behaviors[MODE.SMART_CIRCLE] = SmartCircleBehavior
Behaviors[MODE.CHAR_OUTLINE] = CharacterOutlineBehavior
Invisicam:SetMode(STARTING_MODE)
return Invisicam
@@ -0,0 +1,194 @@
-- PopperCam Version 16
-- OnlyTwentyCharacters
local PopperCam = {} -- Guarantees your players won't see outside the bounds of your map!
-----------------
--| Constants |--
-----------------
local POP_RESTORE_RATE = 0.3
local MIN_CAMERA_ZOOM = 0.5
local VALID_SUBJECTS = {
'Humanoid',
'VehicleSeat',
'SkateboardPlatform',
}
local portraitPopperFixFlagExists, portraitPopperFixFlagEnabled = pcall(function()
return UserSettings():IsUserFeatureEnabled("UserPortraitPopperFix")
end)
local FFlagUserPortraitPopperFix = portraitPopperFixFlagExists and portraitPopperFixFlagEnabled
-----------------
--| Variables |--
-----------------
local PlayersService = game:GetService('Players')
local Camera = nil
local CameraSubjectChangeConn = nil
local SubjectPart = nil
local PlayerCharacters = {} -- For ignoring in raycasts
local VehicleParts = {} -- Also just for ignoring
local LastPopAmount = 0
local LastZoomLevel = 0
local PopperEnabled = false
local CFrame_new = CFrame.new
-----------------------
--| Local Functions |--
-----------------------
local math_abs = math.abs
local function OnCameraSubjectChanged()
VehicleParts = {}
local newSubject = Camera.CameraSubject
if newSubject then
-- Determine if we should be popping at all
PopperEnabled = false
for _, subjectType in pairs(VALID_SUBJECTS) do
if newSubject:IsA(subjectType) then
PopperEnabled = true
break
end
end
-- Get all parts of the vehicle the player is controlling
if newSubject:IsA('VehicleSeat') then
VehicleParts = newSubject:GetConnectedParts(true)
end
if FFlagUserPortraitPopperFix then
if newSubject:IsA("BasePart") then
SubjectPart = newSubject
elseif newSubject:IsA("Model") then
SubjectPart = newSubject.PrimaryPart
elseif newSubject:IsA("Humanoid") then
SubjectPart = newSubject.Torso
end
end
end
end
local function OnCharacterAdded(player, character)
PlayerCharacters[player] = character
end
local function OnPlayersChildAdded(child)
if child:IsA('Player') then
child.CharacterAdded:connect(function(character)
OnCharacterAdded(child, character)
end)
if child.Character then
OnCharacterAdded(child, child.Character)
end
end
end
local function OnPlayersChildRemoved(child)
if child:IsA('Player') then
PlayerCharacters[child] = nil
end
end
local function OnWorkspaceChanged(property)
if property == 'CurrentCamera' then
local newCamera = workspace.CurrentCamera
if newCamera then
Camera = newCamera
if CameraSubjectChangeConn then
CameraSubjectChangeConn:disconnect()
end
CameraSubjectChangeConn = Camera:GetPropertyChangedSignal("CameraSubject"):connect(OnCameraSubjectChanged)
OnCameraSubjectChanged()
end
end
end
-------------------------
--| Exposed Functions |--
-------------------------
function PopperCam:Update(EnabledCamera)
if PopperEnabled then
-- First, prep some intermediate vars
local cameraCFrame = Camera.CFrame
local focusPoint = Camera.Focus.p
if FFlagUserPortraitPopperFix and SubjectPart then
focusPoint = SubjectPart.CFrame.p
end
local ignoreList = {}
for _, character in pairs(PlayerCharacters) do
ignoreList[#ignoreList + 1] = character
end
for i = 1, #VehicleParts do
ignoreList[#ignoreList + 1] = VehicleParts[i]
end
-- Get largest cutoff distance
local largest = Camera:GetLargestCutoffDistance(ignoreList)
-- Then check if the player zoomed since the last frame,
-- and if so, reset our pop history so we stop tweening
local zoomLevel = (cameraCFrame.p - focusPoint).Magnitude
if math_abs(zoomLevel - LastZoomLevel) > 0.001 then
LastPopAmount = 0
end
-- Finally, zoom the camera in (pop) by that most-cut-off amount, or the last pop amount if that's more
local popAmount = largest
if LastPopAmount > popAmount then
popAmount = LastPopAmount
end
if popAmount > 0 then
Camera.CFrame = cameraCFrame + (cameraCFrame.lookVector * popAmount)
LastPopAmount = popAmount - POP_RESTORE_RATE -- Shrink it for the next frame
if LastPopAmount < 0 then
LastPopAmount = 0
end
end
LastZoomLevel = zoomLevel
-- Stop shift lock being able to see through walls by manipulating Camera focus inside the wall
if EnabledCamera and EnabledCamera:GetShiftLock() and not EnabledCamera:IsInFirstPerson() then
if EnabledCamera:GetCameraActualZoom() < 1 then
local subjectPosition = EnabledCamera.lastSubjectPosition
if subjectPosition then
Camera.Focus = CFrame_new(subjectPosition)
Camera.CFrame = CFrame_new(subjectPosition - MIN_CAMERA_ZOOM*EnabledCamera:GetCameraLook(), subjectPosition)
end
end
end
end
end
--------------------
--| Script Logic |--
--------------------
-- Connect to the current and all future cameras
workspace.Changed:connect(OnWorkspaceChanged)
OnWorkspaceChanged('CurrentCamera')
-- Connect to all Players so we can ignore their Characters
PlayersService.ChildRemoved:connect(OnPlayersChildRemoved)
PlayersService.ChildAdded:connect(OnPlayersChildAdded)
for _, player in pairs(PlayersService:GetPlayers()) do
OnPlayersChildAdded(player)
end
return PopperCam
@@ -0,0 +1,75 @@
local PlayersService = game:GetService('Players')
local RootCameraCreator = require(script.Parent)
local ZERO_VECTOR2 = Vector2.new(0, 0)
local XZ_VECTOR = Vector3.new(1,0,1)
local Vector2_new = Vector2.new
local CFrame_new = CFrame.new
local math_atan2 = math.atan2
local math_min = math.min
local function IsFinite(num)
return num == num and num ~= 1/0 and num ~= -1/0
end
-- May return NaN or inf or -inf
-- This is a way of finding the angle between the two vectors:
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
local function CreateAttachCamera()
local module = RootCameraCreator()
local lastUpdate = tick()
function module:Update()
local now = tick()
local camera = workspace.CurrentCamera
if lastUpdate == nil or now - lastUpdate > 1 then
module:ResetCameraLook()
self.LastCameraTransform = nil
end
local subjectPosition = self:GetSubjectPosition()
if subjectPosition and camera then
local zoom = self:GetCameraZoom()
if zoom <= 0 then
zoom = 0.1
end
local humanoid = self:GetHumanoid()
if lastUpdate and humanoid and humanoid.Torso then
-- Cap out the delta to 0.1 so we don't get some crazy things when we re-resume from
local delta = math_min(0.1, now - lastUpdate)
local gamepadRotation = self:UpdateGamepad()
self.RotateInput = self.RotateInput + (gamepadRotation * delta)
local forwardVector = humanoid.Torso.CFrame.lookVector
local y = findAngleBetweenXZVectors(forwardVector, self:GetCameraLook())
if IsFinite(y) then
-- Preserve vertical rotation from user input
self.RotateInput = Vector2_new(y, self.RotateInput.Y)
end
end
local newLookVector = self:RotateCamera(self:GetCameraLook(), self.RotateInput)
self.RotateInput = ZERO_VECTOR2
camera.Focus = CFrame_new(subjectPosition)
local newCFrame = CFrame_new(subjectPosition - (zoom * newLookVector), subjectPosition)
camera.CFrame = newCFrame
self.LastCameraTransform = newCFrame
end
lastUpdate = now
end
return module
end
return CreateAttachCamera
@@ -0,0 +1,195 @@
local PlayersService = game:GetService('Players')
local VRService = game:GetService("VRService")
local RootCameraCreator = require(script.Parent)
local UP_VECTOR = Vector3.new(0, 1, 0)
local XZ_VECTOR = Vector3.new(1, 0, 1)
local ZERO_VECTOR2 = Vector2.new(0, 0)
local VR_PITCH_FRACTION = 0.25
local Vector3_new = Vector3.new
local CFrame_new = CFrame.new
local math_min = math.min
local math_max = math.max
local math_atan2 = math.atan2
local math_rad = math.rad
local math_abs = math.abs
local function clamp(low, high, num)
return (num > high and high or num < low and low or num)
end
local function IsFinite(num)
return num == num and num ~= 1/0 and num ~= -1/0
end
local function IsFiniteVector3(vec3)
return IsFinite(vec3.x) and IsFinite(vec3.y) and IsFinite(vec3.z)
end
-- May return NaN or inf or -inf
-- This is a way of finding the angle between the two vectors:
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
local function CreateClassicCamera()
local module = RootCameraCreator()
local tweenAcceleration = math_rad(220)
local tweenSpeed = math_rad(0)
local tweenMaxSpeed = math_rad(250)
local timeBeforeAutoRotate = 2
local lastUpdate = tick()
module.LastUserPanCamera = tick()
function module:Update()
module:ProcessTweens()
local now = tick()
local timeDelta = (now - lastUpdate)
local userPanningTheCamera = (self.UserPanningTheCamera == true)
local camera = workspace.CurrentCamera
local player = PlayersService.LocalPlayer
local humanoid = self:GetHumanoid()
local cameraSubject = camera and camera.CameraSubject
local isInVehicle = cameraSubject and cameraSubject:IsA('VehicleSeat')
local isOnASkateboard = cameraSubject and cameraSubject:IsA('SkateboardPlatform')
if lastUpdate == nil or now - lastUpdate > 1 then
module:ResetCameraLook()
self.LastCameraTransform = nil
end
if lastUpdate then
local gamepadRotation = self:UpdateGamepad()
if self:ShouldUseVRRotation() then
self.RotateInput = self.RotateInput + self:GetVRRotationInput()
else
-- Cap out the delta to 0.1 so we don't get some crazy things when we re-resume from
local delta = math_min(0.1, now - lastUpdate)
if gamepadRotation ~= ZERO_VECTOR2 then
userPanningTheCamera = true
self.RotateInput = self.RotateInput + (gamepadRotation * delta)
end
local angle = 0
if not (isInVehicle or isOnASkateboard) then
angle = angle + (self.TurningLeft and -120 or 0)
angle = angle + (self.TurningRight and 120 or 0)
end
if angle ~= 0 then
self.RotateInput = self.RotateInput + Vector2.new(math_rad(angle * delta), 0)
userPanningTheCamera = true
end
end
end
-- Reset tween speed if user is panning
if userPanningTheCamera then
tweenSpeed = 0
module.LastUserPanCamera = tick()
end
local userRecentlyPannedCamera = now - module.LastUserPanCamera < timeBeforeAutoRotate
local subjectPosition = self:GetSubjectPosition()
if subjectPosition and player and camera then
local zoom = self:GetCameraZoom()
if zoom < 0.5 then
zoom = 0.5
end
if self:GetShiftLock() and not self:IsInFirstPerson() then
-- We need to use the right vector of the camera after rotation, not before
local newLookVector = self:RotateCamera(self:GetCameraLook(), self.RotateInput)
local offset = ((newLookVector * XZ_VECTOR):Cross(UP_VECTOR).unit * 1.75)
if IsFiniteVector3(offset) then
subjectPosition = subjectPosition + offset
end
else
if not userPanningTheCamera and self.LastCameraTransform then
local isInFirstPerson = self:IsInFirstPerson()
if (isInVehicle or isOnASkateboard) and lastUpdate and humanoid and humanoid.Torso then
if isInFirstPerson then
if self.LastSubjectCFrame and (isInVehicle or isOnASkateboard) and cameraSubject:IsA('BasePart') then
local y = -findAngleBetweenXZVectors(self.LastSubjectCFrame.lookVector, cameraSubject.CFrame.lookVector)
if IsFinite(y) then
self.RotateInput = self.RotateInput + Vector2.new(y, 0)
end
tweenSpeed = 0
end
elseif not userRecentlyPannedCamera then
local forwardVector = humanoid.Torso.CFrame.lookVector
if isOnASkateboard then
forwardVector = cameraSubject.CFrame.lookVector
end
tweenSpeed = clamp(0, tweenMaxSpeed, tweenSpeed + tweenAcceleration * timeDelta)
local percent = clamp(0, 1, tweenSpeed * timeDelta)
if self:IsInFirstPerson() then
percent = 1
end
local y = findAngleBetweenXZVectors(forwardVector, self:GetCameraLook())
if IsFinite(y) and math_abs(y) > 0.0001 then
self.RotateInput = self.RotateInput + Vector2.new(y * percent, 0)
end
end
end
end
end
local VREnabled = VRService.VREnabled
camera.Focus = VREnabled and self:GetVRFocus(subjectPosition, timeDelta) or CFrame_new(subjectPosition)
local cameraFocusP = camera.Focus.p
if VREnabled and not self:IsInFirstPerson() then
local cameraHeight = self:GetCameraHeight()
local vecToSubject = (subjectPosition - camera.CFrame.p)
local distToSubject = vecToSubject.magnitude
-- Only move the camera if it exceeded a maximum distance to the subject in VR
if distToSubject > zoom or self.RotateInput.x ~= 0 then
local desiredDist = math_min(distToSubject, zoom)
vecToSubject = self:RotateCamera(vecToSubject.unit * XZ_VECTOR, Vector2.new(self.RotateInput.x, 0)) * desiredDist
local newPos = cameraFocusP - vecToSubject
local desiredLookDir = camera.CFrame.lookVector
if self.RotateInput.x ~= 0 then
desiredLookDir = vecToSubject
end
local lookAt = Vector3.new(newPos.x + desiredLookDir.x, newPos.y, newPos.z + desiredLookDir.z)
self.RotateInput = ZERO_VECTOR2
camera.CFrame = CFrame_new(newPos, lookAt) + Vector3_new(0, cameraHeight, 0)
end
else
local newLookVector = self:RotateCamera(self:GetCameraLook(), self.RotateInput)
self.RotateInput = ZERO_VECTOR2
camera.CFrame = CFrame_new(cameraFocusP - (zoom * newLookVector), cameraFocusP)
end
self.LastCameraTransform = camera.CFrame
self.LastCameraFocus = camera.Focus
if (isInVehicle or isOnASkateboard) and cameraSubject:IsA('BasePart') then
self.LastSubjectCFrame = cameraSubject.CFrame
else
self.LastSubjectCFrame = nil
end
end
lastUpdate = now
end
return module
end
return CreateClassicCamera
@@ -0,0 +1,48 @@
local PlayersService = game:GetService('Players')
local RootCameraCreator = require(script.Parent)
local ZERO_VECTOR2 = Vector2.new(0, 0)
local CFrame_new = CFrame.new
local math_min = math.min
local function CreateFixedCamera()
local module = RootCameraCreator()
local lastUpdate = tick()
function module:Update()
local now = tick()
local camera = workspace.CurrentCamera
local player = PlayersService.LocalPlayer
if lastUpdate == nil or now - lastUpdate > 1 then
module:ResetCameraLook()
self.LastCameraTransform = nil
end
if lastUpdate then
-- Cap out the delta to 0.1 so we don't get some crazy things when we re-resume from
local delta = math_min(0.1, now - lastUpdate)
local gamepadRotation = self:UpdateGamepad()
self.RotateInput = self.RotateInput + (gamepadRotation * delta)
end
local subjectPosition = self:GetSubjectPosition()
if subjectPosition and player and camera then
local zoom = self:GetCameraZoom()
if zoom <= 0 then
zoom = 0.1
end
local newLookVector = self:RotateCamera(self:GetCameraLook(), self.RotateInput)
self.RotateInput = ZERO_VECTOR2
camera.CFrame = CFrame_new(camera.CFrame.p, camera.CFrame.p + (zoom * newLookVector))
self.LastCameraTransform = camera.CFrame
end
lastUpdate = now
end
return module
end
return CreateFixedCamera
@@ -0,0 +1,192 @@
local PlayersService = game:GetService('Players')
local VRService = game:GetService("VRService")
local RootCameraCreator = require(script.Parent)
local CFrame_new = CFrame.new
local Vector2_new = Vector2.new
local Vector3_new = Vector3.new
local math_min = math.min
local math_max = math.max
local math_atan2 = math.atan2
local math_rad = math.rad
local math_abs = math.abs
local HUMANOIDSTATE_CLIMBING = Enum.HumanoidStateType.Climbing
local ZERO_VECTOR2 = Vector2.new(0, 0)
local UP_VECTOR = Vector3.new(0, 1, 0)
local XZ_VECTOR = Vector3.new(1, 0, 1)
local ZERO_VECTOR3 = Vector3.new(0, 0, 0)
local PORTRAIT_OFFSET = Vector3.new(0, -3, 0)
local function clamp(low, high, num)
return num > high and high or num < low and low or num
end
local function IsFinite(num)
return num == num and num ~= 1/0 and num ~= -1/0
end
local function IsFiniteVector3(vec3)
return IsFinite(vec3.x) and IsFinite(vec3.y) and IsFinite(vec3.z)
end
-- May return NaN or inf or -inf
local function findAngleBetweenXZVectors(vec2, vec1)
-- This is a way of finding the angle between the two vectors:
return math_atan2(vec1.X*vec2.Z-vec1.Z*vec2.X, vec1.X*vec2.X + vec1.Z*vec2.Z)
end
local function CreateFollowCamera()
local module = RootCameraCreator()
local tweenAcceleration = math_rad(220)
local tweenSpeed = math_rad(0)
local tweenMaxSpeed = math_rad(250)
local timeBeforeAutoRotate = 2
local lastUpdate = tick()
module.LastUserPanCamera = tick()
function module:Update()
module:ProcessTweens()
local now = tick()
local timeDelta = (now - lastUpdate)
local userPanningTheCamera = (self.UserPanningTheCamera == true)
local camera = workspace.CurrentCamera
local player = PlayersService.LocalPlayer
local humanoid = self:GetHumanoid()
local cameraSubject = camera and camera.CameraSubject
local isClimbing = humanoid and humanoid:GetState() == HUMANOIDSTATE_CLIMBING
local isInVehicle = cameraSubject and cameraSubject:IsA('VehicleSeat')
local isOnASkateboard = cameraSubject and cameraSubject:IsA('SkateboardPlatform')
if lastUpdate == nil or now - lastUpdate > 1 then
module:ResetCameraLook()
self.LastCameraTransform = nil
end
if lastUpdate then
if self:ShouldUseVRRotation() then
self.RotateInput = self.RotateInput + self:GetVRRotationInput()
else
-- Cap out the delta to 0.1 so we don't get some crazy things when we re-resume from
local delta = math_min(0.1, now - lastUpdate)
local angle = 0
-- NOTE: Traditional follow camera does not rotate with arrow keys
if not (isInVehicle or isOnASkateboard) then
angle = angle + (self.TurningLeft and -120 or 0)
angle = angle + (self.TurningRight and 120 or 0)
end
local gamepadRotation = self:UpdateGamepad()
if gamepadRotation ~= Vector2.new(0,0) then
userPanningTheCamera = true
self.RotateInput = self.RotateInput + (gamepadRotation * delta)
end
if angle ~= 0 then
userPanningTheCamera = true
self.RotateInput = self.RotateInput + Vector2_new(math_rad(angle * delta), 0)
end
end
end
-- Reset tween speed if user is panning
if userPanningTheCamera then
tweenSpeed = 0
module.LastUserPanCamera = tick()
end
local userRecentlyPannedCamera = now - module.LastUserPanCamera < timeBeforeAutoRotate
local subjectPosition = self:GetSubjectPosition()
if subjectPosition and player and camera then
local zoom = self:GetCameraZoom()
if zoom < 0.5 then
zoom = 0.5
end
if self:GetShiftLock() and not self:IsInFirstPerson() then
local newLookVector = self:RotateCamera(self:GetCameraLook(), self.RotateInput)
local offset = ((newLookVector * XZ_VECTOR):Cross(UP_VECTOR).unit * 1.75)
if IsFiniteVector3(offset) then
subjectPosition = subjectPosition + offset
end
else
if self.LastCameraTransform and not userPanningTheCamera then
local isInFirstPerson = self:IsInFirstPerson()
if (isClimbing or isInVehicle or isOnASkateboard) and lastUpdate and humanoid and humanoid.Torso then
if isInFirstPerson then
if self.LastSubjectCFrame and (isInVehicle or isOnASkateboard) and cameraSubject:IsA('BasePart') then
local y = -findAngleBetweenXZVectors(self.LastSubjectCFrame.lookVector, cameraSubject.CFrame.lookVector)
if IsFinite(y) then
self.RotateInput = self.RotateInput + Vector2.new(y, 0)
end
tweenSpeed = 0
end
elseif not userRecentlyPannedCamera then
local forwardVector = humanoid.Torso.CFrame.lookVector
if isOnASkateboard then
forwardVector = cameraSubject.CFrame.lookVector
end
tweenSpeed = clamp(0, tweenMaxSpeed, tweenSpeed + tweenAcceleration * timeDelta)
local percent = clamp(0, 1, tweenSpeed*timeDelta)
if not isClimbing and self:IsInFirstPerson() then
percent = 1
end
local y = findAngleBetweenXZVectors(forwardVector, self:GetCameraLook())
-- Check for NaN
if IsFinite(y) and math_abs(y) > 0.0001 then
self.RotateInput = self.RotateInput + Vector2.new(y * percent, 0)
end
end
elseif not (isInFirstPerson or userRecentlyPannedCamera) and not VRService.VREnabled then
local lastVec = -(self.LastCameraTransform.p - subjectPosition)
local y = findAngleBetweenXZVectors(lastVec, self:GetCameraLook())
-- This cutoff is to decide if the humanoid's angle of movement,
-- relative to the camera's look vector, is enough that
-- we want the camera to be following them. The point is to provide
-- a sizable deadzone to allow more precise forward movements.
local thetaCutoff = 0.4
-- Check for NaNs
if IsFinite(y) and math.abs(y) > 0.0001 and math_abs(y) > thetaCutoff*timeDelta then
self.RotateInput = self.RotateInput + Vector2.new(y, 0)
end
end
end
end
local newLookVector = self:RotateCamera(self:GetCameraLook(), self.RotateInput)
self.RotateInput = ZERO_VECTOR2
if VRService.VREnabled then
camera.Focus = self:GetVRFocus(subjectPosition, timeDelta)
elseif self:IsPortraitMode() then
camera.Focus = CFrame_new(subjectPosition + PORTRAIT_OFFSET)
else
camera.Focus = CFrame_new(subjectPosition)
end
camera.CFrame = CFrame_new(camera.Focus.p - (zoom * newLookVector), camera.Focus.p) + Vector3.new(0, self:GetCameraHeight(), 0)
self.LastCameraTransform = camera.CFrame
self.LastCameraFocus = camera.Focus
if isInVehicle or isOnASkateboard and cameraSubject:IsA('BasePart') then
self.LastSubjectCFrame = cameraSubject.CFrame
else
self.LastSubjectCFrame = nil
end
end
lastUpdate = now
end
return module
end
return CreateFollowCamera
@@ -0,0 +1,450 @@
--[[
Orbital Camera 1.0.0
AllYourBlox
Derived from ClassicCamera, adds camera angle constraints, and represents position values in spherical
coordinates (azimuth, elevation, radius), instead of Cartesian coordinates (x, y, z). Azimuth is the
angle of rotation about the Y axis, with the zero-angle reference point corresponding to offsetting
the camera in the +Z direction, from where it will be looking in the -Z direction by default. Elevation
is the angle up from the XZ plane, where zero degrees is on the plane, and +90 degrees is on the +Y
axis. Distance is the camera-to-subject distance, the spherical coordinates radius, specified in studs.
--]]
-- Do not edit these values, they are not the developer-set limits, they are limits
-- to the values the camera system equations can correctly handle
local MIN_ALLOWED_ELEVATION_DEG = -80
local MAX_ALLOWED_ELEVATION_DEG = 80
local externalProperties = {}
externalProperties["InitialDistance"] = 25
externalProperties["MinDistance"] = 10
externalProperties["MaxDistance"] = 100
externalProperties["InitialElevation"] = 35
externalProperties["MinElevation"] = 35
externalProperties["MaxElevation"] = 35
externalProperties["ReferenceAzimuth"] = -45 -- Angle around the Y axis where the camera starts. -45 offsets the camera in the -X and +Z directions equally
externalProperties["CWAzimuthTravel"] = 90 -- How many degrees the camera is allowed to rotate from the reference position, CW as seen from above
externalProperties["CCWAzimuthTravel"] = 90 -- How many degrees the camera is allowed to rotate from the reference position, CCW as seen from above
externalProperties["UseAzimuthLimits"] = false -- Full rotation around Y axis available by default
local refAzimuthRad
local curAzimuthRad
local minAzimuthAbsoluteRad
local maxAzimuthAbsoluteRad
local useAzimuthLimits
local curElevationRad
local minElevationRad
local maxElevationRad
local curDistance
local minDistance
local maxDistance
local UNIT_Z = Vector3.new(0,0,1)
local TAU = 2 * math.pi
local changedSignalConnections = {}
-- End of OrbitalCamera additions
local PlayersService = game:GetService('Players')
local VRService = game:GetService("VRService")
local RootCameraCreator = require(script.Parent)
local UP_VECTOR = Vector3.new(0, 1, 0)
local XZ_VECTOR = Vector3.new(1, 0, 1)
local ZERO_VECTOR2 = Vector2.new(0, 0)
local VR_PITCH_FRACTION = 0.25
local Vector3_new = Vector3.new
local CFrame_new = CFrame.new
local math_min = math.min
local math_max = math.max
local math_atan2 = math.atan2
local math_rad = math.rad
local math_abs = math.abs
--[[ Gamepad Support ]]--
local THUMBSTICK_DEADZONE = 0.2
local r3ButtonDown = false
local l3ButtonDown = false
local currentZoomSpeed = 1 -- Multiplier, so 1 == no zooming
local function clamp(value, minValue, maxValue)
if maxValue < minValue then
maxValue = minValue
end
return math.clamp(value, minValue, maxValue)
end
local function IsFinite(num)
return num == num and num ~= 1/0 and num ~= -1/0
end
local function IsFiniteVector3(vec3)
return IsFinite(vec3.x) and IsFinite(vec3.y) and IsFinite(vec3.z)
end
-- May return NaN or inf or -inf
-- This is a way of finding the angle between the two vectors:
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
local function GetValueObject(name, defaultValue)
local valueObj = script:FindFirstChild(name)
if valueObj then
return valueObj.Value
end
return defaultValue
end
local function LoadOrCreateNumberValueParameter(name, valueType, updateFunction)
local valueObj = script:FindFirstChild(name)
if valueObj and valueObj:isA(valueType) then
-- Value object exists and is the correct type, use its value
externalProperties[name] = valueObj.Value
elseif externalProperties[name] ~= nil then
-- Create missing (or replace incorrectly-typed) valueObject with default value
valueObj = Instance.new(valueType)
valueObj.Name = name
valueObj.Parent = script
valueObj.Value = externalProperties[name]
else
print("externalProperties table has no entry for ",name)
return
end
if updateFunction then
if changedSignalConnections[name] then
changedSignalConnections[name]:disconnect()
end
changedSignalConnections[name] = valueObj.Changed:connect(function(newValue)
externalProperties[name] = newValue
updateFunction()
end)
end
end
local function SetAndBoundsCheckAzimuthValues()
minAzimuthAbsoluteRad = math.rad(externalProperties["ReferenceAzimuth"]) - math.abs(math.rad(externalProperties["CWAzimuthTravel"]))
maxAzimuthAbsoluteRad = math.rad(externalProperties["ReferenceAzimuth"]) + math.abs(math.rad(externalProperties["CCWAzimuthTravel"]))
useAzimuthLimits = externalProperties["UseAzimuthLimits"]
if useAzimuthLimits then
curAzimuthRad = math.max(curAzimuthRad, minAzimuthAbsoluteRad)
curAzimuthRad = math.min(curAzimuthRad, maxAzimuthAbsoluteRad)
end
end
local function SetAndBoundsCheckElevationValues()
-- These degree values are the direct user input values. It is deliberate that they are
-- ranged checked only against the extremes, and not against each other. Any time one
-- is changed, both of the internal values in radians are recalculated. This allows for
-- A developer to change the values in any order and for the end results to be that the
-- internal values adjust to match intent as best as possible.
local minElevationDeg = math.max(externalProperties["MinElevation"], MIN_ALLOWED_ELEVATION_DEG)
local maxElevationDeg = math.min(externalProperties["MaxElevation"], MAX_ALLOWED_ELEVATION_DEG)
-- Set internal values in radians
minElevationRad = math.rad(math.min(minElevationDeg, maxElevationDeg))
maxElevationRad = math.rad(math.max(minElevationDeg, maxElevationDeg))
curElevationRad = math.max(curElevationRad, minElevationRad)
curElevationRad = math.min(curElevationRad, maxElevationRad)
end
local function SetAndBoundsCheckDistanceValues()
minDistance = externalProperties["MinDistance"]
maxDistance = externalProperties["MaxDistance"]
curDistance = math.max(curDistance, minDistance)
curDistance = math.min(curDistance, maxDistance)
end
-- This loads from, or lazily creates, NumberValue objects for exposed parameters
local function LoadNumberValueParameters()
-- These initial values do not require change listeners since they are read only once
LoadOrCreateNumberValueParameter("InitialElevation", "NumberValue", nil)
LoadOrCreateNumberValueParameter("InitialDistance", "NumberValue", nil)
-- Note: ReferenceAzimuth is also used as an initial value, but needs a change listener because it is used in the calculation of the limits
LoadOrCreateNumberValueParameter("ReferenceAzimuth", "NumberValue", SetAndBoundsCheckAzimuthValues)
LoadOrCreateNumberValueParameter("CWAzimuthTravel", "NumberValue", SetAndBoundsCheckAzimuthValues)
LoadOrCreateNumberValueParameter("CCWAzimuthTravel", "NumberValue", SetAndBoundsCheckAzimuthValues)
LoadOrCreateNumberValueParameter("MinElevation", "NumberValue", SetAndBoundsCheckElevationValues)
LoadOrCreateNumberValueParameter("MaxElevation", "NumberValue", SetAndBoundsCheckElevationValues)
LoadOrCreateNumberValueParameter("MinDistance", "NumberValue", SetAndBoundsCheckDistanceValues)
LoadOrCreateNumberValueParameter("MaxDistance", "NumberValue", SetAndBoundsCheckDistanceValues)
LoadOrCreateNumberValueParameter("UseAzimuthLimits", "BoolValue", SetAndBoundsCheckAzimuthValues)
-- Internal values set (in radians, from degrees), plus sanitization
curAzimuthRad = math.rad(externalProperties["ReferenceAzimuth"])
curElevationRad = math.rad(externalProperties["InitialElevation"])
curDistance = externalProperties["InitialDistance"]
SetAndBoundsCheckAzimuthValues()
SetAndBoundsCheckElevationValues()
SetAndBoundsCheckDistanceValues()
end
local function CreateOrbitalCamera()
local module = RootCameraCreator()
LoadNumberValueParameters()
module.DefaultZoom = curDistance
local tweenAcceleration = math_rad(220)
local tweenSpeed = math_rad(0)
local tweenMaxSpeed = math_rad(250)
local timeBeforeAutoRotate = 2
local lastUpdate = tick()
module.LastUserPanCamera = tick()
function module:Update()
module:ProcessTweens()
local now = tick()
local timeDelta = (now - lastUpdate)
local userPanningTheCamera = (self.UserPanningTheCamera == true)
local camera = workspace.CurrentCamera
local player = PlayersService.LocalPlayer
local humanoid = self:GetHumanoid()
local cameraSubject = camera and camera.CameraSubject
local isInVehicle = cameraSubject and cameraSubject:IsA('VehicleSeat')
local isOnASkateboard = cameraSubject and cameraSubject:IsA('SkateboardPlatform')
if lastUpdate == nil or now - lastUpdate > 1 then
module:ResetCameraLook()
self.LastCameraTransform = nil
end
if lastUpdate then
local gamepadRotation = self:UpdateGamepad()
if self:ShouldUseVRRotation() then
self.RotateInput = self.RotateInput + self:GetVRRotationInput()
else
-- Cap out the delta to 0.1 so we don't get some crazy things when we re-resume from
local delta = math_min(0.1, now - lastUpdate)
if gamepadRotation ~= ZERO_VECTOR2 then
userPanningTheCamera = true
self.RotateInput = self.RotateInput + (gamepadRotation * delta)
end
local angle = 0
if not (isInVehicle or isOnASkateboard) then
angle = angle + (self.TurningLeft and -120 or 0)
angle = angle + (self.TurningRight and 120 or 0)
end
if angle ~= 0 then
self.RotateInput = self.RotateInput + Vector2.new(math_rad(angle * delta), 0)
userPanningTheCamera = true
end
end
end
-- Reset tween speed if user is panning
if userPanningTheCamera then
tweenSpeed = 0
module.LastUserPanCamera = tick()
end
local userRecentlyPannedCamera = now - module.LastUserPanCamera < timeBeforeAutoRotate
local subjectPosition = self:GetSubjectPosition()
if subjectPosition and player and camera then
local zoom = self:ZoomCamera(curDistance * currentZoomSpeed)
if not userPanningTheCamera and self.LastCameraTransform then
local isInFirstPerson = self:IsInFirstPerson()
if (isInVehicle or isOnASkateboard) and lastUpdate and humanoid and humanoid.Torso then
if isInFirstPerson then
if self.LastSubjectCFrame and (isInVehicle or isOnASkateboard) and cameraSubject:IsA('BasePart') then
local y = -findAngleBetweenXZVectors(self.LastSubjectCFrame.lookVector, cameraSubject.CFrame.lookVector)
if IsFinite(y) then
self.RotateInput = self.RotateInput + Vector2.new(y, 0)
end
tweenSpeed = 0
end
elseif not userRecentlyPannedCamera then
local forwardVector = humanoid.Torso.CFrame.lookVector
if isOnASkateboard then
forwardVector = cameraSubject.CFrame.lookVector
end
tweenSpeed = clamp(0, tweenMaxSpeed, tweenSpeed + tweenAcceleration * timeDelta)
local percent = clamp(0, 1, tweenSpeed * timeDelta)
if self:IsInFirstPerson() then
percent = 1
end
local y = findAngleBetweenXZVectors(forwardVector, self:GetCameraLook())
if IsFinite(y) and math_abs(y) > 0.0001 then
self.RotateInput = self.RotateInput + Vector2.new(y * percent, 0)
end
end
end
end
local VREnabled = VRService.VREnabled
camera.Focus = VREnabled and self:GetVRFocus(subjectPosition, timeDelta) or CFrame_new(subjectPosition)
local cameraFocusP = camera.Focus.p
if VREnabled and not self:IsInFirstPerson() then
local cameraHeight = self:GetCameraHeight()
local vecToSubject = (subjectPosition - camera.CFrame.p)
local distToSubject = vecToSubject.magnitude
-- Only move the camera if it exceeded a maximum distance to the subject in VR
if distToSubject > zoom or self.RotateInput.x ~= 0 then
local desiredDist = math_min(distToSubject, zoom)
vecToSubject = self:RotateCamera(vecToSubject.unit * XZ_VECTOR, Vector2.new(self.RotateInput.x, 0)) * desiredDist
local newPos = cameraFocusP - vecToSubject
local desiredLookDir = camera.CFrame.lookVector
if self.RotateInput.x ~= 0 then
desiredLookDir = vecToSubject
end
local lookAt = Vector3.new(newPos.x + desiredLookDir.x, newPos.y, newPos.z + desiredLookDir.z)
self.RotateInput = ZERO_VECTOR2
camera.CFrame = CFrame_new(newPos, lookAt) + Vector3_new(0, cameraHeight, 0)
end
else
-- self.RotateInput is a Vector2 of mouse movement deltas since last update
curAzimuthRad = curAzimuthRad - self.RotateInput.x
if useAzimuthLimits then
curAzimuthRad = clamp(curAzimuthRad, minAzimuthAbsoluteRad, maxAzimuthAbsoluteRad)
else
curAzimuthRad = (curAzimuthRad ~= 0) and (math.sign(curAzimuthRad) * (math.abs(curAzimuthRad) % TAU)) or 0
end
curDistance = clamp(zoom, minDistance, maxDistance)
curElevationRad = clamp(curElevationRad + self.RotateInput.y, minElevationRad,maxElevationRad)
local cameraPosVector = curDistance * ( CFrame.fromEulerAnglesYXZ( -curElevationRad, curAzimuthRad, 0 ) * UNIT_Z )
local camPos = subjectPosition + cameraPosVector
camera.CFrame = CFrame.new(camPos, subjectPosition)
self.RotateInput = ZERO_VECTOR2
end
self.LastCameraTransform = camera.CFrame
self.LastCameraFocus = camera.Focus
if (isInVehicle or isOnASkateboard) and cameraSubject:IsA('BasePart') then
self.LastSubjectCFrame = cameraSubject.CFrame
else
self.LastSubjectCFrame = nil
end
end
lastUpdate = now
end
function module:GetCameraZoom()
return curDistance
end
function module:ZoomCamera(desiredZoom)
local player = PlayersService.LocalPlayer
if player then
curDistance = clamp(desiredZoom, minDistance, maxDistance)
end
local isFirstPerson = self:GetCameraZoom() < 2
--ShiftLockController:SetIsInFirstPerson(isFirstPerson)
-- set mouse behavior
self:UpdateMouseBehavior()
return self:GetCameraZoom()
end
function module:ZoomCameraBy(zoomScale)
local newDist = curDistance
-- Can break into more steps to get more accurate integration
newDist = self:rk4Integrator(curDistance, zoomScale, 1)
self:ZoomCamera(newDist)
return self:GetCameraZoom()
end
function module:ZoomCameraFixedBy(zoomIncrement)
return self:ZoomCamera(self:GetCameraZoom() + zoomIncrement)
end
function module:SetInitialOrientation(humanoid)
local newDesiredLook = (humanoid.Torso.CFrame.lookVector - Vector3.new(0,0.23,0)).unit
local horizontalShift = findAngleBetweenXZVectors(newDesiredLook, self:GetCameraLook())
local vertShift = math.asin(self:GetCameraLook().y) - math.asin(newDesiredLook.y)
if not IsFinite(horizontalShift) then
horizontalShift = 0
end
if not IsFinite(vertShift) then
vertShift = 0
end
self.RotateInput = Vector2.new(horizontalShift, vertShift)
end
function module.getGamepadPan(name, state, input)
if input.UserInputType == module.activeGamepad and input.KeyCode == Enum.KeyCode.Thumbstick2 then
if r3ButtonDown or l3ButtonDown then
-- R3 or L3 Thumbstick is depressed, right stick controls dolly in/out
if (input.Position.Y > THUMBSTICK_DEADZONE) then
currentZoomSpeed = 0.96
elseif (input.Position.Y < -THUMBSTICK_DEADZONE) then
currentZoomSpeed = 1.04
else
currentZoomSpeed = 1.00
end
else
if state == Enum.UserInputState.Cancel then
module.GamepadPanningCamera = ZERO_VECTOR2
return
end
local inputVector = Vector2.new(input.Position.X, -input.Position.Y)
if inputVector.magnitude > THUMBSTICK_DEADZONE then
module.GamepadPanningCamera = Vector2.new(input.Position.X, -input.Position.Y)
else
module.GamepadPanningCamera = ZERO_VECTOR2
end
end
end
end
function module.doGamepadZoom(name, state, input)
if input.UserInputType == module.activeGamepad and (input.KeyCode == Enum.KeyCode.ButtonR3 or input.KeyCode == Enum.KeyCode.ButtonL3) then
if (state == Enum.UserInputState.Begin) then
r3ButtonDown = input.KeyCode == Enum.KeyCode.ButtonR3
l3ButtonDown = input.KeyCode == Enum.KeyCode.ButtonL3
elseif (state == Enum.UserInputState.End) then
if (input.KeyCode == Enum.KeyCode.ButtonR3) then
r3ButtonDown = false
elseif (input.KeyCode == Enum.KeyCode.ButtonL3) then
l3ButtonDown = false
end
if (not r3ButtonDown) and (not l3ButtonDown) then
currentZoomSpeed = 1.00
end
end
end
end
function module:BindGamepadInputActions()
local ContextActionService = game:GetService('ContextActionService')
ContextActionService:BindAction("OrbitalCamGamepadPan", module.getGamepadPan, false, Enum.KeyCode.Thumbstick2)
ContextActionService:BindAction("OrbitalCamGamepadZoom", module.doGamepadZoom, false, Enum.KeyCode.ButtonR3)
ContextActionService:BindAction("OrbitalCamGamepadZoomAlt", module.doGamepadZoom, false, Enum.KeyCode.ButtonL3)
end
return module
end
return CreateOrbitalCamera
@@ -0,0 +1,12 @@
local RootCameraCreator = require(script.Parent)
local function CreateScriptableCamera()
local module = RootCameraCreator()
function module:Update()
end
return module
end
return CreateScriptableCamera
@@ -0,0 +1,54 @@
local PlayersService = game:GetService('Players')
local RootCameraCreator = require(script.Parent)
local ZERO_VECTOR2 = Vector2.new(0, 0)
local CFrame_new = CFrame.new
local math_min = math.min
local function CreateTrackCamera()
local module = RootCameraCreator()
local lastUpdate = tick()
function module:Update()
local now = tick()
local userPanningTheCamera = (self.UserPanningTheCamera == true)
local camera = workspace.CurrentCamera
local player = PlayersService.LocalPlayer
if lastUpdate == nil or now - lastUpdate > 1 then
module:ResetCameraLook()
self.LastCameraTransform = nil
end
if lastUpdate then
-- Cap out the delta to 0.1 so we don't get some crazy things when we re-resume from
local delta = math_min(0.1, now - lastUpdate)
local gamepadRotation = self:UpdateGamepad()
if gamepadRotation ~= ZERO_VECTOR2 then
userPanningTheCamera = true
self.RotateInput = self.RotateInput + (gamepadRotation * delta)
end
end
local subjectPosition = self:GetSubjectPosition()
if subjectPosition and player and camera then
local zoom = self:GetCameraZoom()
if zoom <= 0 then
zoom = 0.1
end
local newLookVector = self:RotateCamera(self:GetCameraLook(), self.RotateInput)
self.RotateInput = ZERO_VECTOR2
camera.Focus = CFrame_new(subjectPosition)
camera.CFrame = CFrame_new(subjectPosition - (zoom * newLookVector), subjectPosition)
self.LastCameraTransform = camera.CoordinateFrame
end
lastUpdate = now
end
return module
end
return CreateTrackCamera
@@ -0,0 +1,260 @@
local PlayersService = game:GetService('Players')
local UserInputService = game:GetService('UserInputService')
local VRService = game:GetService("VRService")
local ContextActionService = game:GetService("ContextActionService")
local LocalPlayer = PlayersService.LocalPlayer
local RootCameraCreator = require(script.Parent)
local XZ_VECTOR = Vector3.new(1, 0, 1)
local ZERO_VECTOR2 = Vector2.new(0, 0)
local PRESNAP_TIME_OFFSET = 0.5 --seconds
local PRESNAP_TIME_LATCH = PRESNAP_TIME_OFFSET * 10
local HEIGHT_OFFSET = 3
local HORZ_OFFSET = 4
local function CreateVRCamera()
local module = RootCameraCreator()
module.AllowOcclusion = false
local lastUpdate = tick()
local forceSnap = true
local forceSnapPoint = nil
local lastLook = Vector3.new(0, 0, -1)
local movementUpdateEventConn = nil
local lastSnapTimeEstimate = math.huge
local snapId = 0
local waitingForSnap = false
local snappedHeadOffset = VRService:GetUserCFrame(Enum.UserCFrame.Head).p
local snapPendingWhileJumping = false
local isJumping = false
local autoSnapsPaused = false
local currentDestination = nil
local function forceSnapTo(snapPoint)
forceSnap = true
forceSnapPoint = snapPoint
snapId = snapId + 1
waitingForSnap = false
end
local function onMovementUpdateEvent(updateType, arg1, arg2)
if updateType == "targetPoint" then
currentDestination = arg1
end
if updateType == "timing" then
local estimatedTimeRemaining = arg1
local snapPoint = arg2
if waitingForSnap and estimatedTimeRemaining > lastSnapTimeEstimate then
--our estimate grew, so cancel this snap and potentially re-evaluate it
waitingForSnap = false
snapId = snapId + 1
end
if estimatedTimeRemaining < PRESNAP_TIME_LATCH and estimatedTimeRemaining > PRESNAP_TIME_OFFSET then
waitingForSnap = true
snapId = snapId + 1
local thisSnapId = snapId
local timeToWait = estimatedTimeRemaining - PRESNAP_TIME_OFFSET
coroutine.wrap(function()
wait(timeToWait)
if waitingForSnap and snapId == thisSnapId then
waitingForSnap = false
forceSnap = true
forceSnapPoint = snapPoint
end
end)()
end
elseif updateType == "shortPath" or updateType == "pathFailure" or updateType == "offtrack" and not autoSnapsPaused then
if isJumping then
snapPendingWhileJumping = true
return
end
local snapPoint = arg1
forceSnapTo(snapPoint)
elseif updateType == "force" then
snapPendingWhileJumping = false
isJumping = false
forceSnapTo(nil)
end
end
local function onResetCameraAction(actionName, inputState, inputObj)
if inputState == Enum.UserInputState.Begin then
autoSnapsPaused = true
onMovementUpdateEvent("force", nil, nil)
else
autoSnapsPaused = false
end
end
local function bindActions(bind)
if bind then
ContextActionService:BindActionAtPriority("ResetCameraVR", onResetCameraAction, false, Enum.ContextActionPriority.Low.Value, Enum.KeyCode.ButtonL2)
else
autoSnapsPaused = false
ContextActionService:UnbindAction("ResetCameraVR")
end
end
local lastKnownTorsoPosition = Vector3.new()
local function onCharacterAdded(character)
local humanoid = character:WaitForChild("Humanoid")
humanoid.StateChanged:connect(function(oldState, newState)
local camera = workspace.CurrentCamera
if not camera or camera.CameraSubject ~= humanoid or not VRService.VREnabled then
return
end
if newState == Enum.HumanoidStateType.Jumping then
isJumping = true
elseif newState == Enum.HumanoidStateType.Landed then
if snapPendingWhileJumping then
forceSnapTo(nil)
snapPendingWhileJumping = false
end
isJumping = false
elseif newState == Enum.HumanoidStateType.Dead then
forceSnapTo(nil)
elseif newState == Enum.HumanoidStateType.Swimming then
if isJumping and snapPendingWhileJumping then
--Jumped into water and let go of controls during flight, treat as a normal landing
forceSnapTo(nil)
snapPendingWhileJumping = false
end
isJumping = false
end
end)
local humanoidRootPart = humanoid.Torso
humanoidRootPart.Changed:connect(function(property)
local camera = workspace.CurrentCamera
local cameraSubject = camera.CameraSubject
if camera and cameraSubject == humanoid and property == "CFrame" or property == "Position" then
if (humanoidRootPart.Position - lastKnownTorsoPosition).magnitude > 5 then
forceSnapTo(nil)
end
end
end)
end
if LocalPlayer.Character then
onCharacterAdded(LocalPlayer.Character)
end
LocalPlayer.CharacterAdded:connect(onCharacterAdded)
spawn(function()
local rootCamera = script.Parent
if not rootCamera then return end
local cameraScript = rootCamera.Parent
if not cameraScript then return end
local playerScripts = cameraScript.Parent
if not playerScripts then return end
local controlScript = playerScripts:WaitForChild("ControlScript")
local masterControlModule = controlScript:WaitForChild("MasterControl")
local vrNavigationModule = masterControlModule:WaitForChild("VRNavigation")
local movementUpdateEvent = vrNavigationModule:WaitForChild("MovementUpdate")
movementUpdateEventConn = movementUpdateEvent.Event:connect(onMovementUpdateEvent)
end)
local onCameraSubjectChangedConn = nil
local function onCameraSubjectChanged()
local camera = workspace.CurrentCamera
if camera and camera.CameraSubject then
delay(1, function () forceSnap = true end)
end
end
local function onCurrentCameraChanged()
if onCameraSubjectChangedConn then
onCameraSubjectChangedConn:disconnect()
onCameraSubjectChangedConn = nil
end
if workspace.CurrentCamera then
onCameraSubjectChangedConn = workspace.CurrentCamera:GetPropertyChangedSignal("CameraSubject"):connect(onCameraSubjectChanged)
onCameraSubjectChanged()
end
end
workspace:GetPropertyChangedSignal("CurrentCamera"):connect(onCurrentCameraChanged)
onCurrentCameraChanged()
local function onVREnabled()
bindActions(VRService.VREnabled)
end
VRService:GetPropertyChangedSignal("VREnabled"):connect(onVREnabled)
function module:Update()
local now = tick()
local timeDelta = now - lastUpdate
local camera = workspace.CurrentCamera
local cameraSubject = camera and camera.CameraSubject
local player = PlayersService.LocalPlayer
local subjectPosition = self:GetSubjectPosition()
local zoom = self:GetCameraZoom()
local subjectPosition = self:GetSubjectPosition()
local gamepadRotation = self:UpdateGamepad()
if subjectPosition and currentDestination then
local dist = (currentDestination - subjectPosition).magnitude
if dist < 10 then
forceSnap = true
forceSnapPoint = currentDestination
currentDestination = nil
end
end
if cameraSubject and cameraSubject:IsA("Humanoid") then
local rootPart = cameraSubject.RootPart
if rootPart then
lastKnownTorsoPosition = rootPart.Position
end
end
local look = lastLook
if subjectPosition and forceSnap then
forceSnap = false
local newFocusPoint = subjectPosition
if forceSnapPoint then
newFocusPoint = Vector3.new(forceSnapPoint.X, subjectPosition.Y, forceSnapPoint.Z)
end
camera.Focus = CFrame.new(newFocusPoint)
forceSnapPoint = nil
look = camera:GetRenderCFrame().lookVector
snappedHeadOffset = VRService:GetUserCFrame(Enum.UserCFrame.Head).p
end
if subjectPosition and player and camera then
local cameraFocusP = camera.Focus.p
self.RotateInput = ZERO_VECTOR2
look = (look * XZ_VECTOR).unit
camera.CFrame = CFrame.new(cameraFocusP - (HORZ_OFFSET * look)) + Vector3.new(0, HEIGHT_OFFSET, 0) - snappedHeadOffset
self.LastCameraTransform = camera.CFrame
self.LastCameraFocus = camera.Focus
end
lastLook = look
lastUpdate = now
end
return module
end
return CreateVRCamera
@@ -0,0 +1,63 @@
local PlayersService = game:GetService('Players')
local RootCameraCreator = require(script.Parent)
local ZERO_VECTOR2 = Vector2.new(0, 0)
local CFrame_new = CFrame.new
local function CreateWatchCamera()
local module = RootCameraCreator()
module.PanEnabled = false
local lastUpdate = tick()
function module:Update()
local now = tick()
local camera = workspace.CurrentCamera
local player = PlayersService.LocalPlayer
if lastUpdate == nil or now - lastUpdate > 1 then
module:ResetCameraLook()
self.LastZoom = nil
end
local subjectPosition = self:GetSubjectPosition()
if subjectPosition and player and camera then
local cameraLook = nil
local humanoid = self:GetHumanoid()
if humanoid and humanoid.Torso then
-- TODO: let the paging buttons move the camera but not the mouse/touch
-- currently neither do
local diffVector = subjectPosition - camera.CFrame.p
cameraLook = diffVector.unit
if self.LastZoom and self.LastZoom == self:GetCameraZoom() then
-- Don't clobber the zoom if they zoomed the camera
local zoom = diffVector.magnitude
self:ZoomCamera(zoom)
end
end
local zoom = self:GetCameraZoom()
if zoom <= 0 then
zoom = 0.1
end
local newLookVector = self:RotateVector(cameraLook or self:GetCameraLook(), self.RotateInput)
self.RotateInput = ZERO_VECTOR2
local newFocus = CFrame_new(subjectPosition)
local newCamCFrame = CFrame_new(newFocus.p - (zoom * newLookVector), subjectPosition)
camera.Focus = newFocus
camera.CFrame = newCamCFrame
self.LastZoom = zoom
end
lastUpdate = now
end
return module
end
return CreateWatchCamera
@@ -0,0 +1,206 @@
--[[
// FileName: ShiftLockController
// Written by: jmargh
// Version 1.2
// Description: Manages the state of shift lock mode
// Required by:
RootCamera
// Note: ContextActionService sinks keys, so until we allow binding to ContextActionService without sinking
// keys, this module will use UserInputService.
--]]
local Players = game:GetService('Players')
local UserInputService = game:GetService('UserInputService')
-- Settings and GameSettings are read only
local Settings = UserSettings() -- ignore warning
local GameSettings = Settings.GameSettings
local ShiftLockController = {}
--[[ Script Variables ]]--
while not Players.LocalPlayer do
Players.PlayerAdded:wait()
end
local LocalPlayer = Players.LocalPlayer
local Mouse = LocalPlayer:GetMouse()
local PlayerGui = LocalPlayer:WaitForChild('PlayerGui')
local ScreenGui = nil
local ShiftLockIcon = nil
local InputCn = nil
local IsShiftLockMode = false
local IsShiftLocked = false
local IsActionBound = false
local IsInFirstPerson = false
-- Toggle Event
ShiftLockController.OnShiftLockToggled = Instance.new('BindableEvent')
-- wrapping long conditional in function
local function isShiftLockMode()
return LocalPlayer.DevEnableMouseLock and GameSettings.ControlMode == Enum.ControlMode.MouseLockSwitch and
LocalPlayer.DevComputerMovementMode ~= Enum.DevComputerMovementMode.ClickToMove and
GameSettings.ComputerMovementMode ~= Enum.ComputerMovementMode.ClickToMove and
LocalPlayer.DevComputerMovementMode ~= Enum.DevComputerMovementMode.Scriptable
end
if not UserInputService.TouchEnabled then -- TODO: Remove when safe on mobile
IsShiftLockMode = isShiftLockMode()
end
--[[ Constants ]]--
local SHIFT_LOCK_OFF = 'rbxasset://textures/ui/mouseLock_off.png'
local SHIFT_LOCK_ON = 'rbxasset://textures/ui/mouseLock_on.png'
local SHIFT_LOCK_CURSOR = 'rbxasset://textures/MouseLockedCursor.png'
--[[ Local Functions ]]--
local function onShiftLockToggled()
IsShiftLocked = not IsShiftLocked
if IsShiftLocked then
ShiftLockIcon.Image = SHIFT_LOCK_ON
Mouse.Icon = SHIFT_LOCK_CURSOR
else
ShiftLockIcon.Image = SHIFT_LOCK_OFF
Mouse.Icon = ""
end
ShiftLockController.OnShiftLockToggled:Fire()
end
local function initialize()
if ScreenGui then
ScreenGui:Destroy()
ScreenGui = nil
end
ScreenGui = Instance.new('ScreenGui')
ScreenGui.Name = "ControlGui"
local frame = Instance.new('Frame')
frame.Name = "BottomLeftControl"
frame.Size = UDim2.new(0, 130, 0, 46)
frame.Position = UDim2.new(0, 0, 1, -46)
frame.BackgroundTransparency = 1
frame.Parent = ScreenGui
ShiftLockIcon = Instance.new('ImageButton')
ShiftLockIcon.Name = "MouseLockLabel"
ShiftLockIcon.Size = UDim2.new(0, 31, 0, 31)
ShiftLockIcon.Position = UDim2.new(0, 12, 0, 2)
ShiftLockIcon.BackgroundTransparency = 1
ShiftLockIcon.Image = IsShiftLocked and SHIFT_LOCK_ON or SHIFT_LOCK_OFF
ShiftLockIcon.Visible = true
ShiftLockIcon.Parent = frame
ShiftLockIcon.MouseButton1Click:connect(onShiftLockToggled)
ScreenGui.Parent = IsShiftLockMode and PlayerGui or nil
end
--[[ Public API ]]--
function ShiftLockController:IsShiftLocked()
return IsShiftLockMode and IsShiftLocked
end
function ShiftLockController:SetIsInFirstPerson(isInFirstPerson)
IsInFirstPerson = isInFirstPerson
end
--[[ Input/Settings Changed Events ]]--
local mouseLockSwitchFunc = function(actionName, inputState, inputObject)
if IsShiftLockMode then
onShiftLockToggled()
end
end
local function disableShiftLock()
if ScreenGui then ScreenGui.Parent = nil end
IsShiftLockMode = false
Mouse.Icon = ""
if InputCn then
InputCn:disconnect()
InputCn = nil
end
IsActionBound = false
ShiftLockController.OnShiftLockToggled:Fire()
end
-- TODO: Remove when we figure out ContextActionService without sinking keys
local function onShiftInputBegan(inputObject, isProcessed)
if isProcessed then return end
if inputObject.UserInputType == Enum.UserInputType.Keyboard and
(inputObject.KeyCode == Enum.KeyCode.LeftShift or inputObject.KeyCode == Enum.KeyCode.RightShift) then
--
mouseLockSwitchFunc()
end
end
local function enableShiftLock()
IsShiftLockMode = isShiftLockMode()
if IsShiftLockMode then
if ScreenGui then
ScreenGui.Parent = PlayerGui
end
if IsShiftLocked then
Mouse.Icon = SHIFT_LOCK_CURSOR
ShiftLockController.OnShiftLockToggled:Fire()
end
if not IsActionBound then
InputCn = UserInputService.InputBegan:connect(onShiftInputBegan)
IsActionBound = true
end
end
end
GameSettings.Changed:connect(function(property)
if property == 'ControlMode' then
if GameSettings.ControlMode == Enum.ControlMode.MouseLockSwitch then
enableShiftLock()
else
disableShiftLock()
end
elseif property == 'ComputerMovementMode' then
if GameSettings.ComputerMovementMode == Enum.ComputerMovementMode.ClickToMove then
disableShiftLock()
else
enableShiftLock()
end
end
end)
LocalPlayer.Changed:connect(function(property)
if property == 'DevEnableMouseLock' then
if LocalPlayer.DevEnableMouseLock then
enableShiftLock()
else
disableShiftLock()
end
elseif property == 'DevComputerMovementMode' then
if LocalPlayer.DevComputerMovementMode == Enum.DevComputerMovementMode.ClickToMove or
LocalPlayer.DevComputerMovementMode == Enum.DevComputerMovementMode.Scriptable then
--
disableShiftLock()
else
enableShiftLock()
end
end
end)
LocalPlayer.CharacterAdded:connect(function(character)
-- we need to recreate guis on character load
if not UserInputService.TouchEnabled then
initialize()
end
end)
--[[ Initialization ]]--
-- TODO: Remove when safe! ContextActionService crashes touch clients with tupele is 2 or more
if not UserInputService.TouchEnabled then
initialize()
if isShiftLockMode() then
InputCn = UserInputService.InputBegan:connect(onShiftInputBegan)
IsActionBound = true
end
end
return ShiftLockController
@@ -0,0 +1,190 @@
-- SolarCrane
local MAX_TWEEN_RATE = 2.8 -- per second
local function clamp(low, high, num)
return (num > high and high or num < low and low or num)
end
local math_floor = math.floor
local function Round(num, places)
local decimalPivot = 10^places
return math_floor(num * decimalPivot + 0.5) / decimalPivot
end
local function CreateTransparencyController()
local module = {}
local LastUpdate = tick()
local TransparencyDirty = false
local Enabled = false
local LastTransparency = nil
local DescendantAddedConn, DescendantRemovingConn = nil, nil
local ToolDescendantAddedConns = {}
local ToolDescendantRemovingConns = {}
local CachedParts = {}
local function HasToolAncestor(object)
if object.Parent == nil then return false end
return object.Parent:IsA('Tool') or HasToolAncestor(object.Parent)
end
local function IsValidPartToModify(part)
if part:IsA('BasePart') or part:IsA('Decal') then
return not HasToolAncestor(part)
end
return false
end
local function CachePartsRecursive(object)
if object then
if IsValidPartToModify(object) then
CachedParts[object] = true
TransparencyDirty = true
end
for _, child in pairs(object:GetChildren()) do
CachePartsRecursive(child)
end
end
end
local function TeardownTransparency()
for child, _ in pairs(CachedParts) do
child.LocalTransparencyModifier = 0
end
CachedParts = {}
TransparencyDirty = true
LastTransparency = nil
if DescendantAddedConn then
DescendantAddedConn:disconnect()
DescendantAddedConn = nil
end
if DescendantRemovingConn then
DescendantRemovingConn:disconnect()
DescendantRemovingConn = nil
end
for object, conn in pairs(ToolDescendantAddedConns) do
conn:disconnect()
ToolDescendantAddedConns[object] = nil
end
for object, conn in pairs(ToolDescendantRemovingConns) do
conn:disconnect()
ToolDescendantRemovingConns[object] = nil
end
end
local function SetupTransparency(character)
TeardownTransparency()
if DescendantAddedConn then DescendantAddedConn:disconnect() end
DescendantAddedConn = character.DescendantAdded:connect(function(object)
-- This is a part we want to invisify
if IsValidPartToModify(object) then
CachedParts[object] = true
TransparencyDirty = true
-- There is now a tool under the character
elseif object:IsA('Tool') then
if ToolDescendantAddedConns[object] then ToolDescendantAddedConns[object]:disconnect() end
ToolDescendantAddedConns[object] = object.DescendantAdded:connect(function(toolChild)
CachedParts[toolChild] = nil
if toolChild:IsA('BasePart') or toolChild:IsA('Decal') then
-- Reset the transparency
toolChild.LocalTransparencyModifier = 0
end
end)
if ToolDescendantRemovingConns[object] then ToolDescendantRemovingConns[object]:disconnect() end
ToolDescendantRemovingConns[object] = object.DescendantRemoving:connect(function(formerToolChild)
wait() -- wait for new parent
if character and formerToolChild and formerToolChild:IsDescendantOf(character) then
if IsValidPartToModify(formerToolChild) then
CachedParts[formerToolChild] = true
TransparencyDirty = true
end
end
end)
end
end)
if DescendantRemovingConn then DescendantRemovingConn:disconnect() end
DescendantRemovingConn = character.DescendantRemoving:connect(function(object)
if CachedParts[object] then
CachedParts[object] = nil
-- Reset the transparency
object.LocalTransparencyModifier = 0
end
end)
CachePartsRecursive(character)
end
function module:SetEnabled(newState)
if Enabled ~= newState then
Enabled = newState
self:Update()
end
end
function module:SetSubject(subject)
local character = nil
if subject and subject:IsA("Humanoid") then
character = subject.Parent
end
if subject and subject:IsA("VehicleSeat") and subject.Occupant then
character = subject.Occupant.Parent
end
if character then
SetupTransparency(character)
else
TeardownTransparency()
end
end
function module:Update()
local instant = false
local now = tick()
local currentCamera = workspace.CurrentCamera
if currentCamera then
local transparency = 0
if not Enabled then
instant = true
else
local distance = (currentCamera.Focus.p - currentCamera.CoordinateFrame.p).magnitude
transparency = (7 - distance) / 5
if transparency < 0.5 then
transparency = 0
end
if LastTransparency then
local deltaTransparency = transparency - LastTransparency
-- Don't tween transparency if it is instant or your character was fully invisible last frame
if not instant and transparency < 1 and LastTransparency < 0.95 then
local maxDelta = MAX_TWEEN_RATE * (now - LastUpdate)
deltaTransparency = clamp(-maxDelta, maxDelta, deltaTransparency)
end
transparency = LastTransparency + deltaTransparency
else
TransparencyDirty = true
end
transparency = clamp(0, 1, Round(transparency, 2))
end
if TransparencyDirty or LastTransparency ~= transparency then
for child, _ in pairs(CachedParts) do
child.LocalTransparencyModifier = transparency
end
TransparencyDirty = false
LastTransparency = transparency
end
end
LastUpdate = now
end
return module
end
return CreateTransparencyController
@@ -0,0 +1,487 @@
--[[
// FileName: ControlScript.lua
// Version 1.1
// Written by: jmargh and jeditkacheff
// Description: Manages in game controls for both touch and keyboard/mouse devices.
// This script will be inserted into PlayerScripts under each player by default. If you want to
// create your own custom controls or modify these controls, you must place a script with this
// name, ControlScript, under StarterPlayer -> PlayerScripts.
// Required Modules:
ClickToMove
DPad
KeyboardMovement
Thumbpad
Thumbstick
TouchJump
MasterControl
VehicleController
--]]
--[[ Services ]]--
local ContextActionService = game:GetService('ContextActionService')
local Players = game:GetService('Players')
local UserInputService = game:GetService('UserInputService')
local VRService = game:GetService('VRService')
-- Settings and GameSettings are read only
local Settings = UserSettings()
local GameSettings = Settings.GameSettings
-- Issue with play solo? (F6)
while not UserInputService.KeyboardEnabled and not UserInputService.TouchEnabled and not UserInputService.GamepadEnabled do
wait()
end
--[[ Script Variables ]]--
while not Players.LocalPlayer do
wait()
end
local lastInputType = nil
local LocalPlayer = Players.LocalPlayer
local PlayerGui = LocalPlayer:WaitForChild('PlayerGui')
local IsTouchDevice = UserInputService.TouchEnabled
local UserMovementMode = IsTouchDevice and GameSettings.TouchMovementMode or GameSettings.ComputerMovementMode
local DevMovementMode = IsTouchDevice and LocalPlayer.DevTouchMovementMode or LocalPlayer.DevComputerMovementMode
local IsUserChoice = (IsTouchDevice and DevMovementMode == Enum.DevTouchMovementMode.UserChoice) or (DevMovementMode == Enum.DevComputerMovementMode.UserChoice)
local TouchGui = nil
local TouchControlFrame = nil
local IsModalEnabled = UserInputService.ModalEnabled
local BindableEvent_OnFailStateChanged = nil
local isJumpEnabled = false
-- register what control scripts we are using
do
local PlayerScripts = LocalPlayer:WaitForChild("PlayerScripts")
local canRegisterControls = pcall(function() PlayerScripts:RegisterTouchMovementMode(Enum.TouchMovementMode.Default) end)
if canRegisterControls then
PlayerScripts:RegisterTouchMovementMode(Enum.TouchMovementMode.Thumbstick)
PlayerScripts:RegisterTouchMovementMode(Enum.TouchMovementMode.DPad)
PlayerScripts:RegisterTouchMovementMode(Enum.TouchMovementMode.Thumbpad)
PlayerScripts:RegisterTouchMovementMode(Enum.TouchMovementMode.ClickToMove)
PlayerScripts:RegisterTouchMovementMode(Enum.TouchMovementMode.DynamicThumbstick)
PlayerScripts:RegisterComputerMovementMode(Enum.ComputerMovementMode.Default)
PlayerScripts:RegisterComputerMovementMode(Enum.ComputerMovementMode.KeyboardMouse)
PlayerScripts:RegisterComputerMovementMode(Enum.ComputerMovementMode.ClickToMove)
end
end
local DynamicThumbstickAvailable = pcall(function()
return Enum.DevTouchMovementMode.DynamicThumbstick and Enum.TouchMovementMode.DynamicThumbstick
end)
local FFlagUserNoCameraClickToMoveSuccess, FFlagUserNoCameraClickToMoveResult = pcall(function() return UserSettings():IsUserFeatureEnabled("UserNoCameraClickToMove") end)
local FFlagUserNoCameraClickToMove = FFlagUserNoCameraClickToMoveSuccess and FFlagUserNoCameraClickToMoveResult
--[[ Modules ]]--
local ClickToMoveTouchControls = nil
local ControlModules = {}
local ControlState = {}
ControlState.Current = nil
function ControlState:SwitchTo(newControl)
if ControlState.Current == newControl then return end
if ControlState.Current then
ControlState.Current:Disable()
end
ControlState.Current = newControl
if ControlState.Current then
ControlState.Current:Enable()
end
end
function ControlState:IsTouchJumpModuleUsed()
return isJumpEnabled
end
local MasterControl = require(script:WaitForChild('MasterControl'))
--MasterControl needs access to ControlState in order to be able to fully enable and disable control
MasterControl.ControlState = ControlState
local DynamicThumbstickModule = require(script.MasterControl:WaitForChild('DynamicThumbstick'))
local ThumbstickModule = require(script.MasterControl:WaitForChild('Thumbstick'))
local ThumbpadModule = require(script.MasterControl:WaitForChild('Thumbpad'))
local DPadModule = require(script.MasterControl:WaitForChild('DPad'))
local DefaultModule = ControlModules.Thumbstick
local TouchJumpModule = require(script.MasterControl:WaitForChild('TouchJump'))
local ClickToMoveModule = FFlagUserNoCameraClickToMove and require(script.MasterControl:WaitForChild('ClickToMoveController')) or nil
MasterControl.TouchJumpModule = TouchJumpModule
local VRNavigationModule = require(script.MasterControl:WaitForChild('VRNavigation'))
local keyboardModule = require(script.MasterControl:WaitForChild('KeyboardMovement'))
ControlModules.Gamepad = require(script.MasterControl:WaitForChild('Gamepad'))
function getTouchModule()
local module = nil
if not IsUserChoice then
if DynamicThumbstickAvailable and DevMovementMode == Enum.DevTouchMovementMode.DynamicThumbstick then
module = DynamicThumbstickModule
isJumpEnabled = true
elseif DevMovementMode == Enum.DevTouchMovementMode.Thumbstick then
module = ThumbstickModule
isJumpEnabled = true
elseif DevMovementMode == Enum.DevTouchMovementMode.Thumbpad then
module = ThumbpadModule
isJumpEnabled = true
elseif DevMovementMode == Enum.DevTouchMovementMode.DPad then
module = DPadModule
isJumpEnabled = false
elseif DevMovementMode == Enum.DevTouchMovementMode.ClickToMove then
if FFlagUserNoCameraClickToMove then
module = ClickToMoveModule
isJumpEnabled = false -- TODO: What should this be, true or false?
else
module = nil
end
elseif DevMovementMode == Enum.DevTouchMovementMode.Scriptable then
module = nil
end
else
if DynamicThumbstickAvailable and UserMovementMode == Enum.TouchMovementMode.DynamicThumbstick then
module = DynamicThumbstickModule
isJumpEnabled = true
elseif UserMovementMode == Enum.TouchMovementMode.Default or UserMovementMode == Enum.TouchMovementMode.Thumbstick then
module = ThumbstickModule
isJumpEnabled = true
elseif UserMovementMode == Enum.TouchMovementMode.Thumbpad then
module = ThumbpadModule
isJumpEnabled = true
elseif UserMovementMode == Enum.TouchMovementMode.DPad then
module = DPadModule
isJumpEnabled = false
elseif UserMovementMode == Enum.TouchMovementMode.ClickToMove then
if FFlagUserNoCameraClickToMove then
module = ClickToMoveModule
isJumpEnabled = false -- TODO: What should this be, true or false?
else
module = nil
end
end
end
return module
end
function setJumpModule(isEnabled)
if not isEnabled then
TouchJumpModule:Disable()
elseif ControlState.Current == ControlModules.Touch then
TouchJumpModule:Enable()
end
end
function setClickToMove()
if DevMovementMode == Enum.DevTouchMovementMode.ClickToMove or DevMovementMode == Enum.DevComputerMovementMode.ClickToMove or
UserMovementMode == Enum.ComputerMovementMode.ClickToMove or UserMovementMode == Enum.TouchMovementMode.ClickToMove then
if lastInputType == Enum.UserInputType.Touch then
ClickToMoveTouchControls = ControlState.Current
end
elseif ClickToMoveTouchControls then
ClickToMoveTouchControls:Disable()
ClickToMoveTouchControls = nil
end
end
ControlModules.Touch = {}
ControlModules.Touch.Current = nil
ControlModules.Touch.LocalPlayerChangedCon = nil
ControlModules.Touch.GameSettingsChangedCon = nil
function ControlModules.Touch:RefreshControlStyle()
if ControlModules.Touch.Current then
ControlModules.Touch.Current:Disable()
end
setJumpModule(false)
TouchJumpModule:Disable()
ControlModules.Touch:Enable()
end
function ControlModules.Touch:DisconnectEvents()
if ControlModules.Touch.LocalPlayerChangedCon then
ControlModules.Touch.LocalPlayerChangedCon:disconnect()
ControlModules.Touch.LocalPlayerChangedCon = nil
end
if ControlModules.Touch.GameSettingsChangedCon then
ControlModules.Touch.GameSettingsChangedCon:disconnect()
ControlModules.Touch.GameSettingsChangedCon = nil
end
end
function ControlModules.Touch:Enable()
DevMovementMode = LocalPlayer.DevTouchMovementMode
IsUserChoice = DevMovementMode == Enum.DevTouchMovementMode.UserChoice
if IsUserChoice then
UserMovementMode = GameSettings.TouchMovementMode
end
local newModuleToEnable = getTouchModule()
if newModuleToEnable then
setClickToMove()
setJumpModule(isJumpEnabled)
newModuleToEnable:Enable()
ControlModules.Touch.Current = newModuleToEnable
if isJumpEnabled then TouchJumpModule:Enable() end
end
-- This being within the above if statement was causing issues with ClickToMove, which isn't a module within this script.
ControlModules.Touch:DisconnectEvents()
ControlModules.Touch.LocalPlayerChangedCon = LocalPlayer:GetPropertyChangedSignal("DevTouchMovementMode"):connect(function()
ControlModules.Touch:RefreshControlStyle()
end)
ControlModules.Touch.GameSettingsChangedCon = GameSettings:GetPropertyChangedSignal("TouchMovementMode"):connect(function()
ControlModules.Touch:RefreshControlStyle()
end)
end
function ControlModules.Touch:Disable()
ControlModules.Touch:DisconnectEvents()
local newModuleToDisable = getTouchModule()
if newModuleToDisable == ThumbstickModule or
newModuleToDisable == DPadModule or
newModuleToDisable == ThumbpadModule or
newModuleToDisable == DynamicThumbstickModule then
newModuleToDisable:Disable()
setJumpModule(false)
TouchJumpModule:Disable()
end
-- UserMovementMode will still have the previous value at this point
if FFlagUserNoCameraClickToMove and UserMovementMode == Enum.ComputerMovementMode.ClickToMove then
ClickToMoveModule:Disable()
end
end
local function getKeyboardModule()
-- NOTE: Click to move still uses keyboard. Leaving cases in case this ever changes.
local whichModule = nil
if not IsUserChoice then
if DevMovementMode == Enum.DevComputerMovementMode.KeyboardMouse then
whichModule = keyboardModule
elseif DevMovementMode == Enum.DevComputerMovementMode.ClickToMove then
whichModule = keyboardModule
end
else
if UserMovementMode == Enum.ComputerMovementMode.KeyboardMouse or UserMovementMode == Enum.ComputerMovementMode.Default then
whichModule = keyboardModule
elseif UserMovementMode == Enum.ComputerMovementMode.ClickToMove then
whichModule = keyboardModule
end
end
return whichModule
end
ControlModules.Keyboard = {}
function ControlModules.Keyboard:RefreshControlStyle()
ControlModules.Keyboard:Disable()
ControlModules.Keyboard:Enable()
end
function ControlModules.Keyboard:Enable()
DevMovementMode = LocalPlayer.DevComputerMovementMode
IsUserChoice = DevMovementMode == Enum.DevComputerMovementMode.UserChoice
if IsUserChoice then
UserMovementMode = GameSettings.ComputerMovementMode
end
local newModuleToEnable = getKeyboardModule()
if newModuleToEnable then
newModuleToEnable:Enable()
end
if FFlagUserNoCameraClickToMove and UserMovementMode == Enum.ComputerMovementMode.ClickToMove then
ClickToMoveModule:Enable()
end
ControlModules.Keyboard:DisconnectEvents()
ControlModules.Keyboard.LocalPlayerChangedCon = LocalPlayer.Changed:connect(function(property)
if property == 'DevComputerMovementMode' then
ControlModules.Keyboard:RefreshControlStyle()
end
end)
ControlModules.Keyboard.GameSettingsChangedCon = GameSettings.Changed:connect(function(property)
if property == 'ComputerMovementMode' then
ControlModules.Keyboard:RefreshControlStyle()
end
end)
end
function ControlModules.Keyboard:DisconnectEvents()
if ControlModules.Keyboard.LocalPlayerChangedCon then
ControlModules.Keyboard.LocalPlayerChangedCon:disconnect()
ControlModules.Keyboard.LocalPlayerChangedCon = nil
end
if ControlModules.Keyboard.GameSettingsChangedCon then
ControlModules.Keyboard.GameSettingsChangedCon:disconnect()
ControlModules.Keyboard.GameSettingsChangedCon = nil
end
end
function ControlModules.Keyboard:Disable()
ControlModules.Keyboard:DisconnectEvents()
local newModuleToDisable = getKeyboardModule()
if newModuleToDisable then
newModuleToDisable:Disable()
end
-- UserMovementMode will still be set to previous movement type
if FFlagUserNoCameraClickToMove and UserMovementMode == Enum.ComputerMovementMode.ClickToMove then
ClickToMoveModule:Disable()
end
end
ControlModules.VRNavigation = {}
function ControlModules.VRNavigation:Enable()
VRNavigationModule:Enable()
end
function ControlModules.VRNavigation:Disable()
VRNavigationModule:Disable()
end
if not FFlagUserNoCameraClickToMove and IsTouchDevice then
BindableEvent_OnFailStateChanged = script.Parent:WaitForChild("OnClickToMoveFailStateChange")
end
-- not used, but needs to be required
local VehicleController = require(script.MasterControl:WaitForChild('VehicleController'))
--[[ Initialization/Setup ]]--
local function createTouchGuiContainer()
if TouchGui then TouchGui:Destroy() end
-- Container for all touch device guis
TouchGui = Instance.new('ScreenGui')
TouchGui.Name = "TouchGui"
TouchGui.ResetOnSpawn = false
TouchGui.Parent = PlayerGui
TouchControlFrame = Instance.new('Frame')
TouchControlFrame.Name = "TouchControlFrame"
TouchControlFrame.Size = UDim2.new(1, 0, 1, 0)
TouchControlFrame.BackgroundTransparency = 1
TouchControlFrame.Parent = TouchGui
ThumbstickModule:Create(TouchControlFrame)
DPadModule:Create(TouchControlFrame)
ThumbpadModule:Create(TouchControlFrame)
TouchJumpModule:Create(TouchControlFrame)
DynamicThumbstickModule:Create(TouchControlFrame)
end
--[[ Settings Changed Connections ]]--
LocalPlayer.Changed:connect(function(property)
if lastInputType == Enum.UserInputType.Touch and property == 'DevTouchMovementMode' then
ControlState:SwitchTo(ControlModules.Touch)
elseif UserInputService.KeyboardEnabled and property == 'DevComputerMovementMode' then
ControlState:SwitchTo(ControlModules.Keyboard)
end
end)
GameSettings.Changed:connect(function(property)
if not IsUserChoice then return end
if property == 'TouchMovementMode' or property == 'ComputerMovementMode' then
UserMovementMode = GameSettings[property]
if property == 'TouchMovementMode' then
ControlState:SwitchTo(ControlModules.Touch)
elseif property == 'ComputerMovementMode' then
ControlState:SwitchTo(ControlModules.Keyboard)
end
end
end)
--[[ Touch Events ]]--
UserInputService.Changed:connect(function(property)
if property == 'ModalEnabled' then
IsModalEnabled = UserInputService.ModalEnabled
if lastInputType == Enum.UserInputType.Touch then
if ControlState.Current == ControlModules.Touch and IsModalEnabled then
ControlState:SwitchTo(nil)
elseif ControlState.Current == nil and not IsModalEnabled then
ControlState:SwitchTo(ControlModules.Touch)
end
end
end
end)
if FFlagUserNoCameraClickToMove then
BindableEvent_OnFailStateChanged = MasterControl:GetClickToMoveFailStateChanged()
end
if BindableEvent_OnFailStateChanged then
BindableEvent_OnFailStateChanged.Event:connect(function(isOn)
if lastInputType == Enum.UserInputType.Touch and ClickToMoveTouchControls then
if isOn then
ControlState:SwitchTo(ClickToMoveTouchControls)
else
ControlState:SwitchTo(nil)
end
end
end)
end
local switchToInputType = function(newLastInputType)
lastInputType = newLastInputType
if VRService.VREnabled then
ControlState:SwitchTo(ControlModules.VRNavigation)
return
end
if lastInputType == Enum.UserInputType.Touch then
ControlState:SwitchTo(ControlModules.Touch)
elseif lastInputType == Enum.UserInputType.Keyboard or
lastInputType == Enum.UserInputType.MouseButton1 or
lastInputType == Enum.UserInputType.MouseButton2 or
lastInputType == Enum.UserInputType.MouseButton3 or
lastInputType == Enum.UserInputType.MouseWheel or
lastInputType == Enum.UserInputType.MouseMovement then
ControlState:SwitchTo(ControlModules.Keyboard)
elseif lastInputType == Enum.UserInputType.Gamepad1 or
lastInputType == Enum.UserInputType.Gamepad2 or
lastInputType == Enum.UserInputType.Gamepad3 or
lastInputType == Enum.UserInputType.Gamepad4 then
ControlState:SwitchTo(ControlModules.Gamepad)
end
end
if IsTouchDevice then
createTouchGuiContainer()
end
MasterControl:Init()
UserInputService.GamepadDisconnected:connect(function(gamepadEnum)
local connectedGamepads = UserInputService:GetConnectedGamepads()
if #connectedGamepads > 0 then return end
if not VRService.VREnabled then
if UserInputService.KeyboardEnabled then
ControlState:SwitchTo(ControlModules.Keyboard)
elseif IsTouchDevice then
ControlState:SwitchTo(ControlModules.Touch)
end
end
end)
UserInputService.GamepadConnected:connect(function(gamepadEnum)
if not VRService.VREnabled then
ControlState:SwitchTo(ControlModules.Gamepad)
end
end)
switchToInputType(UserInputService:GetLastInputType())
UserInputService.LastInputTypeChanged:connect(switchToInputType)
VRService:GetPropertyChangedSignal("VREnabled"):Connect(function()
if VRService.VREnabled then
ControlState:SwitchTo(ControlModules.VRNavigation)
end
end)
@@ -0,0 +1,174 @@
--[[
// FileName: MasterControl
// Version 1.0
// Written by: jeditkacheff
// Description: All character control scripts go thru this script, this script makes sure all actions are performed
--]]
-- [[ Constants ]]--
local ZERO_VECTOR3 = Vector3.new(0, 0, 0)
local STATE_JUMPING = Enum.HumanoidStateType.Jumping
local STATE_FREEFALL = Enum.HumanoidStateType.Freefall
local STATE_LANDED = Enum.HumanoidStateType.Landed
--[[ Local Variables ]]--
local MasterControl = {}
local Players = game:GetService('Players')
local RunService = game:GetService('RunService')
while not Players.LocalPlayer do
Players.PlayerAdded:wait()
end
local LocalPlayer = Players.LocalPlayer
local LocalCharacter = LocalPlayer.Character
local CachedHumanoid = nil
local isJumping = false
local moveValue = Vector3.new(0, 0, 0)
local isJumpEnabled = true
local areControlsEnabled = true
local clickToMoveFailStateChanged = Instance.new("BindableEvent")
clickToMoveFailStateChanged.Name = "ClickToMoveFailStateChanged"
--[[ Local Functions ]]--
function MasterControl:GetHumanoid()
if LocalCharacter then
if CachedHumanoid then
return CachedHumanoid
else
CachedHumanoid = LocalCharacter:FindFirstChildOfClass("Humanoid")
return CachedHumanoid
end
end
end
local characterAncestryChangedConn = nil
local characterChildRemovedConn = nil
local function characterAdded(character)
if characterAncestryChangedConn then
characterAncestryChangedConn:disconnect()
end
if characterChildRemovedConn then
characterChildRemovedConn:disconnect()
end
LocalCharacter = character
CachedHumanoid = LocalCharacter:FindFirstChildOfClass("Humanoid")
characterAncestryChangedConn = character.AncestryChanged:connect(function()
if character.Parent == nil then
LocalCharacter = nil
else
LocalCharacter = character
end
end)
characterChildRemovedConn = character.ChildRemoved:connect(function(child)
if child == CachedHumanoid then
CachedHumanoid = nil
end
end)
end
if LocalCharacter then
characterAdded(LocalCharacter)
end
LocalPlayer.CharacterAdded:connect(characterAdded)
local getHumanoid = MasterControl.GetHumanoid
local moveFunc = LocalPlayer.Move
local updateMovement = function()
if not areControlsEnabled then return end
local humanoid = getHumanoid()
if not humanoid then return end
if isJumpEnabled and isJumping and not humanoid.PlatformStand then
local state = humanoid:GetState()
if state ~= STATE_JUMPING and state ~= STATE_FREEFALL and state ~= STATE_LANDED then
humanoid.Jump = isJumping
end
end
moveFunc(LocalPlayer, moveValue, true)
end
--[[ Public API ]]--
function MasterControl:Init()
RunService:BindToRenderStep("MasterControlStep", Enum.RenderPriority.Input.Value, updateMovement)
end
function MasterControl:Enable()
areControlsEnabled = true
isJumpEnabled = true
if self.ControlState.Current then
self.ControlState.Current:Enable()
end
end
function MasterControl:Disable()
if self.ControlState.Current then
self.ControlState.Current:Disable()
end
--After current control state is disabled, moveValue has been set to zero,
--Call updateMovement one last time to make sure this propagates to the engine -
--Otherwise if disabled while humanoid is moving, humanoid won't stop moving.
updateMovement()
isJumping = false
areControlsEnabled = false
end
function MasterControl:EnableJump()
isJumpEnabled = true
if areControlsEnabled and self.ControlState:IsTouchJumpModuleUsed() then
self.TouchJumpModule:Enable()
end
end
function MasterControl:DisableJump()
isJumpEnabled = false
if self.ControlState:IsTouchJumpModuleUsed() then
self.TouchJumpModule:Disable()
end
end
function MasterControl:AddToPlayerMovement(playerMoveVector)
moveValue = Vector3.new(moveValue.X + playerMoveVector.X, moveValue.Y + playerMoveVector.Y, moveValue.Z + playerMoveVector.Z)
end
function MasterControl:GetMoveVector()
return moveValue
end
function MasterControl:SetIsJumping(jumping)
if not isJumpEnabled then return end
isJumping = jumping
local humanoid = self:GetHumanoid()
if humanoid and not humanoid.PlatformStand then
humanoid.Jump = isJumping
end
end
function MasterControl:DoJump()
if not isJumpEnabled then return end
local humanoid = self:GetHumanoid()
if humanoid then
humanoid.Jump = true
end
end
function MasterControl:GetClickToMoveFailStateChanged()
return clickToMoveFailStateChanged
end
return MasterControl
@@ -0,0 +1,170 @@
--[[
// FileName: DPad
// Version 1.0
// Written by: jmargh
// Description: Implements DPad controls for touch devices
--]]
local Players = game:GetService('Players')
local GuiService = game:GetService('GuiService')
local DPad = {}
local MasterControl = require(script.Parent)
--[[ Script Variables ]]--
while not Players.LocalPlayer do
wait()
end
local LocalPlayer = Players.LocalPlayer
local DPadFrame = nil
local TouchObject = nil
local OnInputEnded = nil -- defined in Create()
--[[ Constants ]]--
local DPAD_SHEET = "rbxasset://textures/ui/DPadSheet.png"
local COMPASS_DIR = {
Vector3.new(1, 0, 0), -- E
Vector3.new(1, 0, 1).unit, -- SE
Vector3.new(0, 0, 1), -- S
Vector3.new(-1, 0, 1).unit, -- SW
Vector3.new(-1, 0, 0), -- W
Vector3.new(-1, 0, -1).unit, -- NW
Vector3.new(0, 0, -1), -- N
Vector3.new(1, 0, -1).unit, -- NE
}
--[[ lua Function Cache ]]--
local ATAN2 = math.atan2
local FLOOR = math.floor
local PI = math.pi
--[[ Local Functions ]]--
local function createArrowLabel(name, position, size, rectOffset, rectSize)
local image = Instance.new('ImageLabel')
image.Name = name
image.Image = DPAD_SHEET
image.ImageRectOffset = rectOffset
image.ImageRectSize = rectSize
image.BackgroundTransparency = 1
image.Size = size
image.Position = position
image.Parent = DPadFrame
return image
end
local function getCenterPosition()
return Vector2.new(DPadFrame.AbsolutePosition.x + DPadFrame.AbsoluteSize.x/2, DPadFrame.AbsolutePosition.y + DPadFrame.AbsoluteSize.y/2)
end
--[[ Public API ]]--
function DPad:Enable()
DPadFrame.Visible = true
end
function DPad:Disable()
DPadFrame.Visible = false
OnInputEnded()
end
function DPad:Create(parentFrame)
if DPadFrame then
DPadFrame:Destroy()
DPadFrame = nil
end
local position = UDim2.new(0, 10, 1, -230)
DPadFrame = Instance.new('Frame')
DPadFrame.Name = "DPadFrame"
DPadFrame.Active = true
DPadFrame.Visible = false
DPadFrame.Size = UDim2.new(0, 192, 0, 192)
DPadFrame.Position = position
DPadFrame.BackgroundTransparency = 1
local smArrowSize = UDim2.new(0, 23, 0, 23)
local lgArrowSize = UDim2.new(0, 64, 0, 64)
local smImgOffset = Vector2.new(46, 46)
local lgImgOffset = Vector2.new(128, 128)
local bBtn = createArrowLabel("BackButton", UDim2.new(0.5, -32, 1, -64), lgArrowSize, Vector2.new(0, 0), lgImgOffset)
local fBtn = createArrowLabel("ForwardButton", UDim2.new(0.5, -32, 0, 0), lgArrowSize, Vector2.new(0, 258), lgImgOffset)
local lBtn = createArrowLabel("LeftButton", UDim2.new(0, 0, 0.5, -32), lgArrowSize, Vector2.new(129, 129), lgImgOffset)
local rBtn = createArrowLabel("RightButton", UDim2.new(1, -64, 0.5, -32), lgArrowSize, Vector2.new(0, 129), lgImgOffset)
local jumpBtn = createArrowLabel("JumpButton", UDim2.new(0.5, -32, 0.5, -32), lgArrowSize, Vector2.new(129, 0), lgImgOffset)
local flBtn = createArrowLabel("ForwardLeftButton", UDim2.new(0, 35, 0, 35), smArrowSize, Vector2.new(129, 258), smImgOffset)
local frBtn = createArrowLabel("ForwardRightButton", UDim2.new(1, -55, 0, 35), smArrowSize, Vector2.new(176, 258), smImgOffset)
flBtn.Visible = false
frBtn.Visible = false
-- input connections
jumpBtn.InputBegan:connect(function(inputObject)
MasterControl:DoJump()
end)
local movementVector = Vector3.new(0,0,0)
local function normalizeDirection(inputPosition)
local jumpRadius = jumpBtn.AbsoluteSize.x/2
local centerPosition = getCenterPosition()
local direction = Vector2.new(inputPosition.x - centerPosition.x, inputPosition.y - centerPosition.y)
if direction.magnitude > jumpRadius then
local angle = ATAN2(direction.y, direction.x)
local octant = (FLOOR(8 * angle / (2 * PI) + 8.5)%8) + 1
movementVector = COMPASS_DIR[octant]
end
if not flBtn.Visible and movementVector == COMPASS_DIR[7] then
flBtn.Visible = true
frBtn.Visible = true
end
end
DPadFrame.InputBegan:connect(function(inputObject)
if TouchObject or inputObject.UserInputType ~= Enum.UserInputType.Touch then
return
end
MasterControl:AddToPlayerMovement(-movementVector)
TouchObject = inputObject
normalizeDirection(TouchObject.Position)
MasterControl:AddToPlayerMovement(movementVector)
end)
DPadFrame.InputChanged:connect(function(inputObject)
if inputObject == TouchObject then
MasterControl:AddToPlayerMovement(-movementVector)
normalizeDirection(TouchObject.Position)
MasterControl:AddToPlayerMovement(movementVector)
MasterControl:SetIsJumping(false)
end
end)
OnInputEnded = function()
TouchObject = nil
flBtn.Visible = false
frBtn.Visible = false
MasterControl:AddToPlayerMovement(-movementVector)
movementVector = Vector3.new(0, 0, 0)
end
DPadFrame.InputEnded:connect(function(inputObject)
if inputObject == TouchObject then
OnInputEnded()
end
end)
GuiService.MenuOpened:connect(function()
if TouchObject then
OnInputEnded()
end
end)
DPadFrame.Parent = parentFrame
end
return DPad
@@ -0,0 +1,618 @@
--[[
// FileName: DynamicThumbstick
// Version 0.9
// Written by: jhelms
// Description: Implements dynamic thumbstick controls for touch devices
--]]
local Players = game:GetService("Players")
local UserInputService = game:GetService("UserInputService")
local GuiService = game:GetService("GuiService")
local RunService = game:GetService("RunService")
local TweenService = game:GetService("TweenService")
local Settings = UserSettings()
local GameSettings = Settings.GameSettings
local MasterControl = require(script.Parent)
local FFlagUserEnableDynamicThumbstickIntroSuccess, FFlagUserEnableDynamicThumbstickIntroResult = pcall(function() return UserSettings():IsUserFeatureEnabled("UserEnableDynamicThumbstickIntro") end)
local FFlagUserEnableDynamicThumbstickIntro = FFlagUserEnableDynamicThumbstickIntroSuccess and FFlagUserEnableDynamicThumbstickIntroResult
local Intro = FFlagUserEnableDynamicThumbstickIntro and require(script:WaitForChild("Intro")) or nil
local Thumbstick = {}
local Enabled = false
--[[ Script Variables ]]--
while not Players.LocalPlayer do
Players.PlayerAdded:wait()
end
local LocalPlayer = Players.LocalPlayer
local Tools = {}
local ToolEquipped = nil
local RevertAutoJumpEnabledToFalse = false
local ThumbstickFrame = nil
local GestureArea = nil
local StartImage = nil
local EndImage = nil
local MiddleImages = {}
local MoveTouchObject = nil
local IsFollowStick = false
local ThumbstickFrame = nil
local OnMoveTouchEnded = nil -- defined in Create()
local OnTouchMovedCn = nil
local OnTouchEndedCn = nil
local TouchActivateCn = nil
local OnRenderSteppedCn = nil
local currentMoveVector = Vector3.new(0,0,0)
local IsFirstTouch = true
--[[ Constants ]]--
local TOUCH_CONTROLS_SHEET = "rbxasset://textures/ui/Input/TouchControlsSheetV2.png"
local MIDDLE_TRANSPARENCIES = {
1 - 0.89,
1 - 0.70,
1 - 0.60,
1 - 0.50,
1 - 0.40,
1 - 0.30,
1 - 0.25
}
local NUM_MIDDLE_IMAGES = #MIDDLE_TRANSPARENCIES
local TOUCH_IS_TAP_TIME_THRESHOLD = 0.5
local TOUCH_IS_TAP_DISTANCE_THRESHOLD = 25
local HasFadedBackgroundInPortrait = false
local HasFadedBackgroundInLandscape = false
local FadeInAndOutBackground = true
local FadeInAndOutMaxAlpha = 0.35
local TweenInAlphaStart = nil
local TweenOutAlphaStart = nil
local FADE_IN_OUT_HALF_DURATION_DEFAULT = 0.3
local FADE_IN_OUT_HALF_DURATION_ORIENTATION_CHANGE = 2
local FADE_IN_OUT_BALANCE_DEFAULT = 0.5
local FadeInAndOutHalfDuration = FADE_IN_OUT_HALF_DURATION_DEFAULT
local FadeInAndOutBalance = FADE_IN_OUT_BALANCE_DEFAULT
local ThumbstickFadeTweenInfo = TweenInfo.new(0.15, Enum.EasingStyle.Quad, Enum.EasingDirection.InOut)
--[[ Local functionality ]]--
local function isDynamicThumbstickEnabled()
return ThumbstickFrame and ThumbstickFrame.Visible
end
local function enableAutoJump(humanoid)
if humanoid and isDynamicThumbstickEnabled() then
local shouldRevert = humanoid.AutoJumpEnabled == false
shouldRevert = shouldRevert and LocalPlayer.DevTouchMovementMode == Enum.DevTouchMovementMode.UserChoice
RevertAutoJumpEnabledToFalse = shouldRevert
humanoid.AutoJumpEnabled = true
end
end
do
local function onCharacterAdded(character)
for _, child in ipairs(LocalPlayer.Character:GetChildren()) do
if child:IsA("Tool") then
ToolEquipped = child
end
end
character.ChildAdded:Connect(function(child)
if child:IsA("Tool") then
ToolEquipped = child
elseif child:IsA("Humanoid") then
enableAutoJump(child)
end
end)
character.ChildRemoved:Connect(function(child)
if child:IsA("Tool") then
if child == ToolEquipped then
ToolEquipped = nil
end
end
end)
local humanoid = character:FindFirstChildOfClass("Humanoid")
if humanoid then
enableAutoJump(humanoid)
end
end
LocalPlayer.CharacterAdded:Connect(onCharacterAdded)
if LocalPlayer.Character then
onCharacterAdded(LocalPlayer.Character)
end
end
--[[ Public API ]]--
function Thumbstick:Enable()
Enabled = true
ThumbstickFrame.Visible = true
local humanoid = MasterControl:GetHumanoid()
enableAutoJump(humanoid)
if FFlagUserEnableDynamicThumbstickIntro and Intro then
coroutine.wrap(function()
--TODO: Remove this pcall when API is stable
local success, shouldShowIntro = pcall(function()
local wasIntroShown = GameSettings:GetOnboardingCompleted("DynamicThumbstick")
return not wasIntroShown
end)
if success and not shouldShowIntro then return end
--Give the game some time to initialize
wait(1)
--Wait to play the intro until the character can move
while true do
if not humanoid then
humanoid = MasterControl:GetHumanoid()
end
if humanoid and humanoid.WalkSpeed ~= 0 and not humanoid.Torso.Anchored then
break
else
wait()
end
end
Intro.play()
end)()
end
end
function Thumbstick:Disable()
Enabled = false
if RevertAutoJumpEnabledToFalse then
local humanoid = MasterControl:GetHumanoid()
if humanoid then
humanoid.AutoJumpEnabled = false
end
end
ThumbstickFrame.Visible = false
OnMoveTouchEnded()
end
function Thumbstick:GetInputObject()
return MoveTouchObject
end
function Thumbstick:Create(parentFrame)
if ThumbstickFrame then
ThumbstickFrame:Destroy()
ThumbstickFrame = nil
if OnTouchMovedCn then
OnTouchMovedCn:disconnect()
OnTouchMovedCn = nil
end
if OnTouchEndedCn then
OnTouchEndedCn:disconnect()
OnTouchEndedCn = nil
end
if OnRenderSteppedCn then
OnRenderSteppedCn:disconnect()
OnRenderSteppedCn = nil
end
if TouchActivateCn then
TouchActivateCn:disconnect()
TouchActivateCn = nil
end
end
local ThumbstickSize = 45
local ThumbstickRingSize = 20
local MiddleSize = 10
local MiddleSpacing = MiddleSize + 4
local RadiusOfDeadZone = 2
local RadiusOfMaxSpeed = 50
local screenSize = parentFrame.AbsoluteSize
local isBigScreen = math.min(screenSize.x, screenSize.y) > 500
if isBigScreen then
ThumbstickSize = ThumbstickSize * 2
ThumbstickRingSize = ThumbstickRingSize * 2
MiddleSize = MiddleSize * 2
MiddleSpacing = MiddleSpacing * 2
RadiusOfDeadZone = RadiusOfDeadZone * 2
RadiusOfMaxSpeed = RadiusOfMaxSpeed * 2
end
local color = Color3.fromRGB(255, 255, 255)
local function layoutThumbstickFrame(portraitMode)
if portraitMode then
ThumbstickFrame.Size = UDim2.new(1, 0, 0.4, 0)
ThumbstickFrame.Position = UDim2.new(0, 0, 0.6, 0)
GestureArea.Size = UDim2.new(1, 0, 0.6, 0)
GestureArea.Position = UDim2.new(0, 0, 0, 0)
else
ThumbstickFrame.Size = UDim2.new(0.4, 0, 2/3, 0)
ThumbstickFrame.Position = UDim2.new(0, 0, 1/3, 0)
GestureArea.Size = UDim2.new(1, 0, 1, 0)
GestureArea.Position = UDim2.new(0, 0, 0, 0)
end
end
GestureArea = Instance.new("Frame")
GestureArea.Name = "GestureArea"
GestureArea.Active = false
GestureArea.Visible = true
GestureArea.BackgroundTransparency = 1
GestureArea.BackgroundColor3 = Color3.fromRGB(0, 0, 0)
ThumbstickFrame = Instance.new('Frame')
ThumbstickFrame.Name = "DynamicThumbstickFrame"
ThumbstickFrame.Active = false
ThumbstickFrame.Visible = false
ThumbstickFrame.BackgroundTransparency = 1.0
ThumbstickFrame.BackgroundColor3 = Color3.fromRGB(0, 0, 0)
layoutThumbstickFrame()
StartImage = Instance.new("ImageLabel")
StartImage.Name = "ThumbstickStart"
StartImage.Visible = true
StartImage.BackgroundTransparency = 1
StartImage.Image = TOUCH_CONTROLS_SHEET
StartImage.ImageRectOffset = Vector2.new(1,1)
StartImage.ImageRectSize = Vector2.new(144, 144)
StartImage.ImageColor3 = Color3.new(0, 0, 0)
StartImage.AnchorPoint = Vector2.new(0.5, 0.5)
StartImage.Position = UDim2.new(0, ThumbstickRingSize * 3.3, 1, -ThumbstickRingSize * 2.8)
StartImage.Size = UDim2.new(0, ThumbstickRingSize * 3.7, 0, ThumbstickRingSize * 3.7)
StartImage.ZIndex = 10
StartImage.Parent = ThumbstickFrame
EndImage = Instance.new("ImageLabel")
EndImage.Name = "ThumbstickEnd"
EndImage.Visible = true
EndImage.BackgroundTransparency = 1
EndImage.Image = TOUCH_CONTROLS_SHEET
EndImage.ImageRectOffset = Vector2.new(1,1)
EndImage.ImageRectSize = Vector2.new(144, 144)
EndImage.AnchorPoint = Vector2.new(0.5, 0.5)
EndImage.Position = StartImage.Position
EndImage.Size = UDim2.new(0, ThumbstickSize * 0.8, 0, ThumbstickSize * 0.8)
EndImage.ZIndex = 10
EndImage.Parent = ThumbstickFrame
for i = 1, NUM_MIDDLE_IMAGES do
MiddleImages[i] = Instance.new("ImageLabel")
MiddleImages[i].Name = "ThumbstickMiddle"
MiddleImages[i].Visible = false
MiddleImages[i].BackgroundTransparency = 1
MiddleImages[i].Image = TOUCH_CONTROLS_SHEET
MiddleImages[i].ImageRectOffset = Vector2.new(1,1)
MiddleImages[i].ImageRectSize = Vector2.new(144, 144)
MiddleImages[i].ImageTransparency = MIDDLE_TRANSPARENCIES[i]
MiddleImages[i].AnchorPoint = Vector2.new(0.5, 0.5)
MiddleImages[i].ZIndex = 9
MiddleImages[i].Parent = ThumbstickFrame
end
if FFlagUserEnableDynamicThumbstickIntro and Intro then
Intro.setup(isBigScreen, parentFrame, GestureArea, ThumbstickFrame, StartImage, EndImage, MiddleImages)
end
local CameraChangedConn = nil
local function onCurrentCameraChanged()
if CameraChangedConn then
CameraChangedConn:Disconnect()
CameraChangedConn = nil
end
local newCamera = workspace.CurrentCamera
if newCamera then
local function onViewportSizeChanged()
local size = newCamera.ViewportSize
local portraitMode = size.X < size.Y
layoutThumbstickFrame(portraitMode)
if FFlagUserEnableDynamicThumbstickIntro then
Intro.setPortraitMode(portraitMode)
end
end
CameraChangedConn = newCamera:GetPropertyChangedSignal("ViewportSize"):Connect(onViewportSizeChanged)
onViewportSizeChanged()
end
end
workspace:GetPropertyChangedSignal("CurrentCamera"):Connect(onCurrentCameraChanged)
if workspace.CurrentCamera then
onCurrentCameraChanged()
end
MoveTouchObject = nil
local MoveTouchStartTime = nil
local MoveTouchStartPosition = nil
local startImageFadeTween, endImageFadeTween, middleImageFadeTweens = nil, nil, {}
local function fadeThumbstick(visible)
if not visible and MoveTouchObject then
return
end
if IsFirstTouch then return end
if startImageFadeTween then
startImageFadeTween:Cancel()
end
if endImageFadeTween then
endImageFadeTween:Cancel()
end
for i = 1, #MiddleImages do
if middleImageFadeTweens[i] then
middleImageFadeTweens[i]:Cancel()
end
end
if visible then
startImageFadeTween = TweenService:Create(StartImage, ThumbstickFadeTweenInfo, { ImageTransparency = 0 })
startImageFadeTween:Play()
endImageFadeTween = TweenService:Create(EndImage, ThumbstickFadeTweenInfo, { ImageTransparency = 0.2 })
endImageFadeTween:Play()
for i = 1, #MiddleImages do
middleImageFadeTweens[i] = TweenService:Create(MiddleImages[i], ThumbstickFadeTweenInfo, { ImageTransparency = MIDDLE_TRANSPARENCIES[i] })
middleImageFadeTweens[i]:Play()
end
else
startImageFadeTween = TweenService:Create(StartImage, ThumbstickFadeTweenInfo, { ImageTransparency = 1 })
startImageFadeTween:Play()
endImageFadeTween = TweenService:Create(EndImage, ThumbstickFadeTweenInfo, { ImageTransparency = 1 })
endImageFadeTween:Play()
for i = 1, #MiddleImages do
middleImageFadeTweens[i] = TweenService:Create(MiddleImages[i], ThumbstickFadeTweenInfo, { ImageTransparency = 1 })
middleImageFadeTweens[i]:Play()
end
end
end
local function fadeThumbstickFrame(fadeDuration, fadeRatio)
FadeInAndOutHalfDuration = fadeDuration * 0.5
FadeInAndOutBalance = fadeRatio
TweenInAlphaStart = tick()
end
if FFlagUserEnableDynamicThumbstickIntro and Intro then
Intro.fadeThumbstick = fadeThumbstick
Intro.fadeThumbstickFrame = fadeThumbstickFrame
end
local function doMove(direction)
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = direction
-- Scaled Radial Dead Zone
local inputAxisMagnitude = currentMoveVector.magnitude
if inputAxisMagnitude < RadiusOfDeadZone then
currentMoveVector = Vector3.new()
else
currentMoveVector = currentMoveVector.unit*(1 - math.max(0, (RadiusOfMaxSpeed - currentMoveVector.magnitude)/RadiusOfMaxSpeed))
currentMoveVector = Vector3.new(currentMoveVector.x, 0, currentMoveVector.y)
end
MasterControl:AddToPlayerMovement(currentMoveVector)
end
local function layoutMiddleImages(startPos, endPos)
local startDist = (ThumbstickSize / 2) + MiddleSize
local vector = endPos - startPos
local distAvailable = vector.magnitude - (ThumbstickRingSize / 2) - MiddleSize
local direction = vector.unit
local distNeeded = MiddleSpacing * NUM_MIDDLE_IMAGES
local spacing = MiddleSpacing
if distNeeded < distAvailable then
spacing = distAvailable / NUM_MIDDLE_IMAGES
end
for i = 1, NUM_MIDDLE_IMAGES do
local image = MiddleImages[i]
local distWithout = startDist + (spacing * (i - 2))
local currentDist = startDist + (spacing * (i - 1))
if distWithout < distAvailable then
local pos = endPos - direction * currentDist
local exposedFraction = math.clamp(1 - ((currentDist - distAvailable) / spacing), 0, 1)
image.Visible = true
image.Position = UDim2.new(0, pos.X, 0, pos.Y)
image.Size = UDim2.new(0, MiddleSize * exposedFraction, 0, MiddleSize * exposedFraction)
else
image.Visible = false
end
end
end
local function moveStick(pos)
local startPos = Vector2.new(MoveTouchStartPosition.X, MoveTouchStartPosition.Y) - ThumbstickFrame.AbsolutePosition
local endPos = Vector2.new(pos.X, pos.Y) - ThumbstickFrame.AbsolutePosition
local relativePosition = endPos - startPos
local length = relativePosition.magnitude
local maxLength = ThumbstickFrame.AbsoluteSize.X
length = math.min(length, maxLength)
relativePosition = relativePosition*length
EndImage.Position = UDim2.new(0, endPos.X, 0, endPos.Y)
layoutMiddleImages(startPos, endPos)
end
-- input connections
ThumbstickFrame.InputBegan:connect(function(inputObject)
if inputObject.UserInputType ~= Enum.UserInputType.Touch or inputObject.UserInputState ~= Enum.UserInputState.Begin then
return
end
if MoveTouchObject then
return
end
if IsFirstTouch then
IsFirstTouch = false
local tweenInfo = TweenInfo.new(0.5, Enum.EasingStyle.Quad, Enum.EasingDirection.Out,0,false,0)
TweenService:Create(StartImage, tweenInfo, {Size = UDim2.new(0, 0, 0, 0)}):Play()
TweenService:Create(EndImage, tweenInfo, {Size = UDim2.new(0, ThumbstickSize, 0, ThumbstickSize), ImageColor3 = Color3.new(0,0,0)}):Play()
end
if FFlagUserEnableDynamicThumbstickIntro and Intro then
Intro.onThumbstickMoveBegin()
end
MoveTouchObject = inputObject
MoveTouchStartTime = tick()
MoveTouchStartPosition = inputObject.Position
local startPosVec2 = Vector2.new(inputObject.Position.X - ThumbstickFrame.AbsolutePosition.X, inputObject.Position.Y - ThumbstickFrame.AbsolutePosition.Y)
StartImage.Visible = true
StartImage.Position = UDim2.new(0, startPosVec2.X, 0, startPosVec2.Y)
EndImage.Visible = true
EndImage.Position = StartImage.Position
fadeThumbstick(true)
moveStick(inputObject.Position)
if FadeInAndOutBackground then
local playerGui = LocalPlayer:FindFirstChildOfClass("PlayerGui")
local hasFadedBackgroundInOrientation = false
-- only fade in/out the background once per orientation
if playerGui then
if playerGui.CurrentScreenOrientation == Enum.ScreenOrientation.LandscapeLeft or
playerGui.CurrentScreenOrientation == Enum.ScreenOrientation.LandscapeRight then
hasFadedBackgroundInOrientation = HasFadedBackgroundInLandscape
HasFadedBackgroundInLandscape = true
elseif playerGui.CurrentScreenOrientation == Enum.ScreenOrientation.Portrait then
hasFadedBackgroundInOrientation = HasFadedBackgroundInPortrait
HasFadedBackgroundInPortrait = true
end
end
if not hasFadedBackgroundInOrientation then
FadeInAndOutHalfDuration = FADE_IN_OUT_HALF_DURATION_DEFAULT
FadeInAndOutBalance = FADE_IN_OUT_BALANCE_DEFAULT
TweenInAlphaStart = tick()
end
end
end)
OnTouchMovedCn = UserInputService.TouchMoved:connect(function(inputObject, isProcessed)
if inputObject == MoveTouchObject then
local direction = Vector2.new(inputObject.Position.x - MoveTouchStartPosition.x, inputObject.Position.y - MoveTouchStartPosition.y)
if math.abs(direction.x) > 0 or math.abs(direction.y) > 0 then
doMove(direction)
moveStick(inputObject.Position)
end
end
end)
OnMoveTouchEnded = function(inputObject)
if inputObject then
local direction = Vector2.new(inputObject.Position.x - MoveTouchStartPosition.x, inputObject.Position.y - MoveTouchStartPosition.y)
if FFlagUserEnableDynamicThumbstickIntro and Intro then
coroutine.wrap(function() Intro.onThumbstickMoved(direction.magnitude) end)()
end
end
MoveTouchObject = nil
fadeThumbstick(false)
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = Vector3.new(0,0,0)
end
OnRenderSteppedCn = RunService.RenderStepped:Connect(function(step)
if TweenInAlphaStart ~= nil then
local delta = tick() - TweenInAlphaStart
local fadeInTime = (FadeInAndOutHalfDuration * 2 * FadeInAndOutBalance)
ThumbstickFrame.BackgroundTransparency = 1 - FadeInAndOutMaxAlpha*math.min(delta/fadeInTime, 1)
if delta > fadeInTime then
TweenOutAlphaStart = tick()
TweenInAlphaStart = nil
end
elseif TweenOutAlphaStart ~= nil then
local delta = tick() - TweenOutAlphaStart
local fadeOutTime = (FadeInAndOutHalfDuration * 2) - (FadeInAndOutHalfDuration * 2 * FadeInAndOutBalance)
ThumbstickFrame.BackgroundTransparency = 1 - FadeInAndOutMaxAlpha + FadeInAndOutMaxAlpha*math.min(delta/fadeOutTime, 1)
if delta > fadeOutTime then
TweenOutAlphaStart = nil
end
end
if FFlagUserEnableDynamicThumbstickIntro and Intro then
if Intro.currentState == Intro.states.MoveThumbstick then
local startPos = StartImage.AbsolutePosition - ThumbstickFrame.AbsolutePosition + (StartImage.AbsoluteSize * 0.5)
local endPos = EndImage.AbsolutePosition - ThumbstickFrame.AbsolutePosition + (EndImage.AbsoluteSize * 0.5)
layoutMiddleImages(startPos, endPos)
end
end
end)
OnTouchEndedCn = UserInputService.TouchEnded:connect(function(inputObject, isProcessed)
if inputObject == MoveTouchObject then
OnMoveTouchEnded(inputObject)
end
end)
GuiService.MenuOpened:connect(function()
if MoveTouchObject then
OnMoveTouchEnded(nil)
end
end)
local playerGui = LocalPlayer:FindFirstChildOfClass("PlayerGui")
while not playerGui do
LocalPlayer.ChildAdded:wait()
playerGui = LocalPlayer:FindFirstChildOfClass("PlayerGui")
end
local playerGuiChangedConn = nil
local originalScreenOrientationWasLandscape = playerGui.CurrentScreenOrientation == Enum.ScreenOrientation.LandscapeLeft or
playerGui.CurrentScreenOrientation == Enum.ScreenOrientation.LandscapeRight
local function longShowBackground()
FadeInAndOutHalfDuration = 2.5
FadeInAndOutBalance = 0.05
TweenInAlphaStart = tick()
end
playerGuiChangedConn = playerGui.Changed:connect(function(prop)
if prop == "CurrentScreenOrientation" then
if (originalScreenOrientationWasLandscape and playerGui.CurrentScreenOrientation == Enum.ScreenOrientation.Portrait) or
(not originalScreenOrientationWasLandscape and playerGui.CurrentScreenOrientation ~= Enum.ScreenOrientation.Portrait) then
playerGuiChangedConn:disconnect()
longShowBackground()
if originalScreenOrientationWasLandscape then
HasFadedBackgroundInPortrait = true
else
HasFadedBackgroundInLandscape = true
end
end
end
end)
GestureArea.Parent = parentFrame.Parent
ThumbstickFrame.Parent = parentFrame
spawn(function()
if game:IsLoaded() then
longShowBackground()
else
game.Loaded:wait()
longShowBackground()
end
end)
end
return Thumbstick
@@ -0,0 +1,522 @@
local TweenService = game:GetService("TweenService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local UserInputService = game:GetService("UserInputService")
local Settings = UserSettings()
local GameSettings = Settings.GameSettings
local LocalPlayer = Players.LocalPlayer
local IMAGE_INTRO_MOVE = "rbxasset://textures/ui/Input/IntroMove.png"
local IMAGE_INTRO_CAMERA = "rbxasset://textures/ui/Input/IntroCamera.png"
local IMAGE_INTRO_CAMERA_PINCH = "rbxasset://textures/ui/Input/IntroCameraPinch.png"
local IMAGE_DASHED_LINE = "rbxasset://textures/ui/Input/DashedLine.png"
local IMAGE_DASHED_LINE_90 = "rbxasset://textures/ui/Input/DashedLine90.png"
local MIDDLE_TRANSPARENCIES = {
1 - 0.69,
1 - 0.50,
1 - 0.40,
1 - 0.30,
1 - 0.20,
1 - 0.10,
1 - 0.05
}
local MOVE_CAMERA_THRESHOLD = 50
local ParentFrame = nil
local GestureArea = nil
local ThumbstickFrame = nil
local StartImage, EndImage, MiddleImages = nil, nil, {}
local IntroMoveImage = nil
local IntroJumpImage = nil
local IntroJumpImageTap = nil
local IntroCameraImage = nil
local IntroCornerAnim = nil
local IntroDashedLineTop, IntroDashedLineSide = nil
local GenericFadeTweenInfo = TweenInfo.new(0.5, Enum.EasingStyle.Quad, Enum.EasingDirection.InOut)
local IntroMoveSpriteSize = 128
local IntroMoveImageSize = 128
local noThumbstickFrameFade = true
local function create(className)
return function(props)
local instance = Instance.new(className)
for key, val in pairs(props) do
if typeof(key) == "string" then
if key ~= "Parent" then
instance[key] = val
end
else
if typeof(val) == "Instance" then
val.Parent = instance
end
end
end
instance.Parent = props.Parent
return instance
end
end
local Intro = {
running = false,
portraitMode = false,
fadeThumbstick = nil,
fadeThumbstickFrame = nil,
didMoveThumbstick = false,
didJump = false,
didMoveCamera = false,
currentState = nil,
states = {},
}
function Intro.setup(isBigScreen, parentFrame, gestureArea, thumbstickFrame, startImage, endImage, middleImages)
ParentFrame = parentFrame
GestureArea = gestureArea
ThumbstickFrame = thumbstickFrame
StartImage = startImage
EndImage = endImage
MiddleImages = middleImages
if isBigScreen then
IntroMoveImageSize = IntroMoveImageSize * 2
end
IntroMoveImage = create("ImageLabel") {
Name = "IntroMoveAnimation",
BackgroundTransparency = 1,
Image = IMAGE_INTRO_MOVE,
AnchorPoint = Vector2.new(102/256, 55/256),
Position = UDim2.new(0.5, 0, 0.5, 0),
Size = UDim2.new(0, IntroMoveImageSize, 0, IntroMoveImageSize),
ImageRectOffset = Vector2.new(IntroMoveSpriteSize, IntroMoveSpriteSize),
ImageRectSize = Vector2.new(IntroMoveSpriteSize, IntroMoveSpriteSize),
ZIndex = 10,
Visible = false,
Parent = EndImage
}
IntroJumpImage = create("ImageLabel") {
Name = "IntroJumpAnimation",
BackgroundTransparency = 1,
AnchorPoint = Vector2.new(102/256, 55/256),
Position = UDim2.new(0.75, 0, 0.25, 0),
Image = IMAGE_INTRO_MOVE,
ImageRectOffset = Vector2.new(0, 0),
ImageRectSize = Vector2.new(IntroMoveSpriteSize, IntroMoveSpriteSize),
ZIndex = 10,
Visible = false,
Parent = ThumbstickFrame
}
IntroJumpImageTap = create("ImageLabel") {
Name = "IntroJumpTapAnimation",
BackgroundTransparency = 1,
Image = IMAGE_INTRO_MOVE,
Position = UDim2.new(0, 0, 0, 0),
AnchorPoint = Vector2.new(0, 0),
Size = UDim2.new(1, 0, 1, 0),
ImageTransparency = 1,
ImageRectOffset = Vector2.new(IntroMoveSpriteSize, 0),
ImageRectSize = Vector2.new(IntroMoveSpriteSize, IntroMoveSpriteSize),
ZIndex = 10,
Visible = false,
Parent = IntroJumpImage
}
IntroCameraImage = create("ImageLabel") {
Name = "IntroCameraDragAnimation",
BackgroundTransparency = 1,
Image = IMAGE_INTRO_MOVE,
ImageRectOffset = Vector2.new(0, IntroMoveSpriteSize),
ImageRectSize = Vector2.new(IntroMoveSpriteSize, IntroMoveSpriteSize),
Position = UDim2.new(0.75, 0, -0.6, 0),
Size = UDim2.new(0, IntroMoveImageSize, 0, IntroMoveImageSize),
AnchorPoint = Vector2.new(0.5, 0),
ZIndex = 10,
Visible = false,
Parent = GestureArea
}
IntroPinchImage = create("ImageLabel") {
Name = "IntroCameraPinchAnimation",
BackgroundTransparency = 1,
Image = IMAGE_INTRO_CAMERA_PINCH,
ImageRectOffset = Vector2.new(0, 0),
ImageRectSize = Vector2.new(IntroMoveSpriteSize, IntroMoveSpriteSize),
Position = UDim2.new(0.95, 0, 0.15, 0),
Size = UDim2.new(0, IntroMoveImageSize, 0, IntroMoveImageSize),
AnchorPoint = Vector2.new(1, 0),
Rotation = 50,
ZIndex = 10,
Visible = false,
Parent = GestureArea
}
IntroDashedLineTop = create("ImageLabel") {
Name = "DashedLine",
BackgroundTransparency = 1,
Position = UDim2.new(0, 0, 0, 0),
Size = UDim2.new(1, -5, 0, 10),
AnchorPoint = Vector2.new(0, 0.5),
Image = IMAGE_DASHED_LINE,
ImageTransparency = 0.5,
ScaleType = Enum.ScaleType.Tile,
TileSize = UDim2.new(0, 64, 0, 10),
Visible = false,
Parent = ThumbstickFrame
}
IntroDashedLineSide = IntroDashedLineTop:Clone()
IntroDashedLineSide.Image = IMAGE_DASHED_LINE_90
IntroDashedLineSide.Position = UDim2.new(1, 0, 0, -5)
IntroDashedLineSide.AnchorPoint = Vector2.new(0.5, 0)
IntroDashedLineSide.Size = UDim2.new(0, 10, 1, 0)
IntroDashedLineSide.TileSize = UDim2.new(0, 10, 0, 64)
IntroDashedLineSide.Parent = ThumbstickFrame
end
function Intro.setPortraitMode(portraitMode)
if not IntroDashedLineSide or not Intro.running then return end
Intro.portraitMode = portraitMode
IntroDashedLineSide.Visible = not portraitMode
end
function Intro.addState(stateName)
local state = {}
state.counter = 0
Intro.states[stateName] = state
return state
end
function Intro.onCompleted()
--TODO: Remove this pcall when API is stable
pcall(function() GameSettings:SetOnboardingCompleted("DynamicThumbstick") end)
local fadeOutTop = TweenService:Create(IntroDashedLineTop, GenericFadeTweenInfo, { ImageTransparency = 1 })
local fadeOutSide = TweenService:Create(IntroDashedLineSide, GenericFadeTweenInfo, { ImageTransparency = 1})
fadeOutTop:Play()
fadeOutSide:Play()
fadeOutTop.Completed:wait()
IntroDashedLineTop.Visible = false
IntroDashedLineSide.Visible = false
Intro.running = false
end
function Intro.setState(newState)
if Intro.currentState == newState then return end
if Intro.currentState then
coroutine.wrap(function() Intro.currentState:stop() end)()
end
Intro.currentState = newState
Intro.currentState.counter = Intro.currentState.counter + 1
Intro.currentState:start()
end
function Intro.repeatState()
if not Intro.currentState then return end
coroutine.wrap(function() Intro.currentState:stop() end)()
Intro.currentState.counter = Intro.currentState.counter + 1
Intro.currentState:start()
end
function Intro.pause()
if not Intro.currentState then return end
Intro.currentState:stop()
Intro.currentState = nil
end
function Intro.onThumbstickMoveBegin()
if Intro.currentState == Intro.states.MoveThumbstick then
Intro.states.MoveThumbstick.startedMoving = true
local moveTween = Intro.states.MoveThumbstick.moveTween
if moveTween then
moveTween:Cancel()
end
end
end
function Intro.onThumbstickMoved(dist)
if Intro.currentState == Intro.states.MoveThumbstick then
if dist > 100 then
Intro.pause()
spawn(function()
wait(0.5)
while StartImage.ImageTransparency ~= 1 do
wait()
end
if Intro.states.MoveThumbstick.counter == 2 then
Intro.setState(Intro.states.MoveCamera)
else
Intro.setState(Intro.states.MoveThumbstick)
end
end)
else
Intro.states.MoveThumbstick.startedMoving = false
end
end
end
function Intro.onJumped()
if Intro.currentState == Intro.states.Jump then
Intro.pause()
spawn(function()
wait(1)
if Intro.states.Jump.counter > 1 then
Intro.setState(Intro.states.MoveCamera)
else
Intro.setState(Intro.states.Jump)
end
end)
end
end
function Intro.onCameraMoved()
if Intro.currentState == Intro.states.MoveCamera then
wait(1)
Intro.setState(Intro.states.ZoomCamera)
end
end
function Intro.onCameraZoomed()
if Intro.currentState == Intro.states.ZoomCamera then
Intro.pause()
end
end
function Intro.play()
for _, state in pairs(Intro.states) do
state.counter = 0
end
Intro.running = true
Intro.currentState = nil
local portraitMode = false
local currentCamera = workspace.CurrentCamera
if currentCamera then
portraitMode = currentCamera.ViewportSize.X < currentCamera.ViewportSize.Y
end
Intro.setPortraitMode(portraitMode)
Intro.setState(Intro.states.MoveThumbstick)
end
Intro.addState("MoveThumbstick") do
function Intro.states.MoveThumbstick:start()
StartImage.Visible = true
EndImage.Visible = true
IntroMoveImage.Visible = true
IntroDashedLineTop.Visible = true
if not Intro.portraitMode then
IntroDashedLineSide.Visible = true
end
self.startedMoving = false
StartImage.Position = UDim2.new(0.5, 0, 0.6, 0)
EndImage.Position = UDim2.new(0.5, 0, 0.6, 0)
local moveTweenTarget = UDim2.new(0.3, 0, -0.25, 0)
if Intro.states.MoveThumbstick.counter % 2 ~= 0 then
moveTweenTarget = UDim2.new(0.7, 0, -0.25, 0)
end
local moveTweenInfo = TweenInfo.new(1.5, Enum.EasingStyle.Quart, Enum.EasingDirection.InOut)
self.moveTween = TweenService:Create(EndImage, moveTweenInfo, { Position = moveTweenTarget })
local moveFadeInfo = TweenInfo.new(0.15, Enum.EasingStyle.Quad, Enum.EasingDirection.InOut)
local fadeOutTween = TweenService:Create(IntroMoveImage, moveFadeInfo, { ImageTransparency = 1 })
local fadeInTween = TweenService:Create(IntroMoveImage, moveFadeInfo, { ImageTransparency = 0 })
self.moveAnimActive = true
coroutine.wrap(function()
while Intro.currentState == self do
if not self.startedMoving then
if not noThumbstickFrameFade then
Intro.fadeThumbstickFrame(moveTweenInfo.Time, 0.05)
end
StartImage.Position = UDim2.new(0.5, 0, 0.6, 0)
EndImage.Position = UDim2.new(0.5, 0, 0.6, 0)
self.moveTween:Play()
Intro.fadeThumbstick(true)
fadeInTween:Play()
self.moveTween.Completed:wait()
if Intro.currentState == self then
Intro.fadeThumbstick(false)
fadeOutTween:Play()
fadeOutTween.Completed:wait()
wait(0.5)
end
else
wait()
end
end
end)()
end
function Intro.states.MoveThumbstick:stop()
self.moveTween:Cancel()
IntroMoveImage.Visible = false
if self.iconOptConn then
self.iconOptConn:disconnect()
self.iconOptConn = nil
end
end
end
Intro.addState("Jump") do
function Intro.states.Jump:start()
IntroJumpImage.Visible = true
IntroJumpImageTap.Visible = true
local jumpImageBaseSize = IntroMoveImageSize
IntroJumpImage.Size = UDim2.new(0, jumpImageBaseSize * 1.5, 0, jumpImageBaseSize * 1.25)
IntroJumpImageTap.ImageTransparency = 1
local fadeInInfo = TweenInfo.new(0.15, Enum.EasingStyle.Quint, Enum.EasingDirection.InOut)
local fadeOutInfo = TweenInfo.new(0.5, Enum.EasingStyle.Quad, Enum.EasingDirection.InOut)
self.fadeHandIn = TweenService:Create(IntroJumpImage, fadeInInfo, { ImageTransparency = 0, Size = UDim2.new(0, jumpImageBaseSize, 0, jumpImageBaseSize * 0.95) })
self.fadeHandOut = TweenService:Create(IntroJumpImage, fadeOutInfo, { ImageTransparency = 0.25, Size = UDim2.new(0, jumpImageBaseSize * 1.25, 0, jumpImageBaseSize * 1.25) })
self.fadeTapIn = TweenService:Create(IntroJumpImageTap, fadeInInfo, { ImageTransparency = 0 })
self.fadeTapOut = TweenService:Create(IntroJumpImageTap, fadeOutInfo, { ImageTransparency = 1 })
coroutine.wrap(function()
while Intro.currentState == self do
self.fadeHandIn:Play()
IntroJumpImageTap.ImageTransparency = 1
if self.iconOptConn then
self.iconOptConn:disconnect()
self.iconOptConn = nil
end
wait(self.fadeHandIn.Completed:wait())
if not noThumbstickFrameFade then
Intro.fadeThumbstickFrame(fadeOutInfo.Time, 0)
end
IntroJumpImageTap.ImageTransparency = 0
self.fadeHandOut:Play()
self.fadeTapOut:Play()
self.fadeHandOut.Completed:wait()
end
end)()
end
function Intro.states.Jump:stop()
IntroJumpImage.Visible = false
IntroJumpImageTap.Visible = false
end
end
Intro.addState("MoveCamera") do
function Intro.states.MoveCamera:start()
IntroCameraImage.Visible = true
local swipeInfo = TweenInfo.new(1, Enum.EasingStyle.Quint, Enum.EasingDirection.InOut)
local swipeTweenLeft = TweenService:Create(IntroCameraImage, swipeInfo, { Position = UDim2.new(0.25, 0, 0.25, 0) })
local swipeTweenRight = TweenService:Create(IntroCameraImage, swipeInfo, { Position = UDim2.new(0.75, 0, 0.25, 0) })
local camera = workspace.CurrentCamera
local cameraLookStart = camera.CFrame.lookVector
coroutine.wrap(function()
while Intro.currentState == self do
swipeTweenLeft:Play()
swipeTweenLeft.Completed:wait()
swipeTweenRight:Play()
swipeTweenRight.Completed:wait()
end
end)()
local function isInCameraArea(touchPos)
return
touchPos.X >= GestureArea.AbsolutePosition.X and touchPos.Y >= GestureArea.AbsolutePosition.Y and
touchPos.X < GestureArea.AbsolutePosition.X + GestureArea.AbsoluteSize.X and
touchPos.Y < GestureArea.AbsolutePosition.Y + GestureArea.AbsoluteSize.Y
end
local touchObj = nil
local recordedMovement = Vector3.new()
self.onInputBeganConn = UserInputService.InputBegan:Connect(function(inputObj, wasProcessed)
if inputObj.UserInputType == Enum.UserInputType.Touch and isInCameraArea(inputObj.Position) and not wasProcessed then
touchObj = inputObj
end
end)
self.onInputChangedConn = UserInputService.InputChanged:Connect(function(inputObj, wasProcessed)
if inputObj == touchObj then
recordedMovement = recordedMovement + inputObj.Delta
if recordedMovement.magnitude > MOVE_CAMERA_THRESHOLD then
IntroCameraImage.Visible = false
end
end
end)
self.onInputEndedConn = UserInputService.InputEnded:Connect(function(inputObj, wasProcessed)
if inputObj == touchObj then
touchObj = nil
if recordedMovement.magnitude > MOVE_CAMERA_THRESHOLD then --todo: make this number a constant
Intro.onCameraMoved()
end
end
end)
end
function Intro.states.MoveCamera:stop()
if self.iconOptConn then
self.iconOptConn:disconnect()
self.iconOptConn = nil
end
IntroCameraImage.Visible = false
end
end
Intro.addState("ZoomCamera") do
function Intro.states.ZoomCamera:start()
IntroPinchImage.Visible = true
local camera = workspace.CurrentCamera
local zoomStart = (camera.Focus.p - camera.CFrame.p).magnitude
coroutine.wrap(function()
while Intro.currentState == self do
IntroPinchImage.ImageRectOffset = Vector2.new(0, 0)
wait(0.75)
IntroPinchImage.ImageRectOffset = Vector2.new(128, 0)
wait(0.25)
end
end)()
coroutine.wrap(function()
while Intro.currentState == self do
local zoom = (camera.Focus.p - camera.CFrame.p).magnitude
if math.abs(zoom - zoomStart) > 3 then
Intro.onCameraZoomed()
end
wait()
end
end)()
end
function Intro.states.ZoomCamera:stop()
IntroPinchImage.Visible = false
Intro.onCompleted()
end
end
return Intro
@@ -0,0 +1,198 @@
--[[
// FileName: Gamepad
// Written by: jeditkacheff
// Description: Implements movement controls for gamepad devices (XBox, PS4, MFi, etc.)
--]]
local Gamepad = {}
local MasterControl = require(script.Parent)
local Players = game:GetService('Players')
local RunService = game:GetService('RunService')
local UserInputService = game:GetService('UserInputService')
local ContextActionService = game:GetService('ContextActionService')
local StarterPlayer = game:GetService('StarterPlayer')
local Settings = UserSettings()
local GameSettings = Settings.GameSettings
local currentMoveVector = Vector3.new(0,0,0)
local activateGamepad = nil
local gamepadConnectedCon = nil
local gamepadDisconnectedCon = nil
while not Players.LocalPlayer do
wait()
end
local LocalPlayer = Players.LocalPlayer
--[[ Constants ]]--
local thumbstickDeadzone = 0.22 --raised from 14% on 3/1/16 to accommodate looser XB360 controllers
function assignActivateGamepad()
local connectedGamepads = UserInputService:GetConnectedGamepads()
if #connectedGamepads > 0 then
for i = 1, #connectedGamepads do
if activateGamepad == nil then
activateGamepad = connectedGamepads[i]
elseif connectedGamepads[i].Value < activateGamepad.Value then
activateGamepad = connectedGamepads[i]
end
end
end
if activateGamepad == nil then -- nothing is connected, at least set up for gamepad1
activateGamepad = Enum.UserInputType.Gamepad1
end
end
--[[ Public API ]]--
function Gamepad:Enable()
local forwardValue = 0
local backwardValue = 0
local leftValue = 0
local rightValue = 0
local moveFunc = LocalPlayer.Move
local gamepadSupports = UserInputService.GamepadSupports
local controlCharacterGamepad = function(actionName, inputState, inputObject)
if inputState == Enum.UserInputState.Cancel then
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = Vector3.new(0,0,0)
return
end
if activateGamepad ~= inputObject.UserInputType then return end
if inputObject.KeyCode ~= Enum.KeyCode.Thumbstick1 then return end
if inputObject.Position.magnitude > thumbstickDeadzone then
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = Vector3.new(inputObject.Position.X, 0, -inputObject.Position.Y)
MasterControl:AddToPlayerMovement(currentMoveVector)
else
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = Vector3.new(0,0,0)
end
end
local jumpCharacterGamepad = function(actionName, inputState, inputObject)
if inputState == Enum.UserInputState.Cancel then
MasterControl:SetIsJumping(false)
return
end
if activateGamepad ~= inputObject.UserInputType then return end
if inputObject.KeyCode ~= Enum.KeyCode.ButtonA then return end
MasterControl:SetIsJumping(inputObject.UserInputState == Enum.UserInputState.Begin)
end
local doDpadMoveUpdate = function(userInputType)
if LocalPlayer and LocalPlayer.Character then
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = Vector3.new(leftValue + rightValue,0,forwardValue + backwardValue)
MasterControl:AddToPlayerMovement(currentMoveVector)
end
end
local moveForwardFunc = function(actionName, inputState, inputObject)
if inputState == Enum.UserInputState.End then
forwardValue = -1
elseif inputState == Enum.UserInputState.Begin or inputState == Enum.UserInputState.Cancel then
forwardValue = 0
end
doDpadMoveUpdate(inputObject.UserInputType)
end
local moveBackwardFunc = function(actionName, inputState, inputObject)
if inputState == Enum.UserInputState.End then
backwardValue = 1
elseif inputState == Enum.UserInputState.Begin or inputState == Enum.UserInputState.Cancel then
backwardValue = 0
end
doDpadMoveUpdate(inputObject.UserInputType)
end
local moveLeftFunc = function(actionName, inputState, inputObject)
if inputState == Enum.UserInputState.End then
leftValue = -1
elseif inputState == Enum.UserInputState.Begin or inputState == Enum.UserInputState.Cancel then
leftValue = 0
end
doDpadMoveUpdate(inputObject.UserInputType)
end
local moveRightFunc = function(actionName, inputState, inputObject)
if inputState == Enum.UserInputState.End then
rightValue = 1
elseif inputState == Enum.UserInputState.Begin or inputState == Enum.UserInputState.Cancel then
rightValue = 0
end
doDpadMoveUpdate(inputObject.UserInputType)
end
local function setActivateGamepad()
if activateGamepad then
ContextActionService:UnbindActivate(activateGamepad, Enum.KeyCode.ButtonR2)
end
assignActivateGamepad()
if activateGamepad then
ContextActionService:BindActivate(activateGamepad, Enum.KeyCode.ButtonR2)
end
end
ContextActionService:BindAction("JumpButton",jumpCharacterGamepad, false, Enum.KeyCode.ButtonA)
ContextActionService:BindAction("MoveThumbstick",controlCharacterGamepad, false, Enum.KeyCode.Thumbstick1)
setActivateGamepad()
if not gamepadSupports(UserInputService, activateGamepad, Enum.KeyCode.Thumbstick1) then
-- if the gamepad supports thumbsticks, theres no point in having the dpad buttons getting eaten up by these actions
ContextActionService:BindAction("forwardDpad", moveForwardFunc, false, Enum.KeyCode.DPadUp)
ContextActionService:BindAction("backwardDpad", moveBackwardFunc, false, Enum.KeyCode.DPadDown)
ContextActionService:BindAction("leftDpad", moveLeftFunc, false, Enum.KeyCode.DPadLeft)
ContextActionService:BindAction("rightDpad", moveRightFunc, false, Enum.KeyCode.DPadRight)
end
gamepadConnectedCon = UserInputService.GamepadDisconnected:connect(function(gamepadEnum)
if activateGamepad ~= gamepadEnum then return end
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = Vector3.new(0,0,0)
activateGamepad = nil
setActivateGamepad()
end)
gamepadDisconnectedCon = UserInputService.GamepadConnected:connect(function(gamepadEnum)
if activateGamepad == nil then
setActivateGamepad()
end
end)
end
function Gamepad:Disable()
ContextActionService:UnbindAction("forwardDpad")
ContextActionService:UnbindAction("backwardDpad")
ContextActionService:UnbindAction("leftDpad")
ContextActionService:UnbindAction("rightDpad")
ContextActionService:UnbindAction("MoveThumbstick")
ContextActionService:UnbindAction("JumpButton")
ContextActionService:UnbindActivate(activateGamepad, Enum.KeyCode.ButtonR2)
if gamepadConnectedCon then gamepadConnectedCon:disconnect() end
if gamepadDisconnectedCon then gamepadDisconnectedCon:disconnect() end
activateGamepad = nil
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = Vector3.new(0,0,0)
MasterControl:SetIsJumping(false)
end
return Gamepad
@@ -0,0 +1,175 @@
--[[
// FileName: ComputerMovementKeyboardMovement
// Version 1.2
// Written by: jeditkacheff/jmargh
// Description: Implements movement controls for keyboard devices
--]]
local Players = game:GetService('Players')
local UserInputService = game:GetService('UserInputService')
local ContextActionService = game:GetService('ContextActionService')
local StarterPlayer = game:GetService('StarterPlayer')
local Settings = UserSettings()
local GameSettings = Settings.GameSettings
local KeyboardMovement = {}
while not Players.LocalPlayer do
wait()
end
local LocalPlayer = Players.LocalPlayer
local CachedHumanoid = nil
local SeatJumpCn = nil
local TextFocusReleasedCn = nil
local TextFocusGainedCn = nil
local WindowFocusReleasedCn = nil
local MasterControl = require(script.Parent)
local currentMoveVector = Vector3.new(0,0,0)
--[[ Local Functions ]]--
local function getHumanoid()
local character = LocalPlayer and LocalPlayer.Character
if character then
if CachedHumanoid and CachedHumanoid.Parent == character then
return CachedHumanoid
else
CachedHumanoid = nil
for _,child in pairs(character:GetChildren()) do
if child:IsA('Humanoid') then
CachedHumanoid = child
return CachedHumanoid
end
end
end
end
end
--[[ Public API ]]--
function KeyboardMovement:Enable()
if not UserInputService.KeyboardEnabled then
return
end
local forwardValue = 0
local backwardValue = 0
local leftValue = 0
local rightValue = 0
local updateMovement = function(inputState)
if inputState == Enum.UserInputState.Cancel then
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = Vector3.new(0, 0, 0)
else
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = Vector3.new(leftValue + rightValue,0,forwardValue + backwardValue)
MasterControl:AddToPlayerMovement(currentMoveVector)
end
end
local moveForwardFunc = function(actionName, inputState, inputObject)
if inputState == Enum.UserInputState.Begin then
forwardValue = -1
elseif inputState == Enum.UserInputState.End or inputState == Enum.UserInputState.Cancel then
forwardValue = 0
end
updateMovement(inputState)
end
local moveBackwardFunc = function(actionName, inputState, inputObject)
if inputState == Enum.UserInputState.Begin then
backwardValue = 1
elseif inputState == Enum.UserInputState.End or inputState == Enum.UserInputState.Cancel then
backwardValue = 0
end
updateMovement(inputState)
end
local moveLeftFunc = function(actionName, inputState, inputObject)
if inputState == Enum.UserInputState.Begin then
leftValue = -1
elseif inputState == Enum.UserInputState.End or inputState == Enum.UserInputState.Cancel then
leftValue = 0
end
updateMovement(inputState)
end
local moveRightFunc = function(actionName, inputState, inputObject)
if inputState == Enum.UserInputState.Begin then
rightValue = 1
elseif inputState == Enum.UserInputState.End or inputState == Enum.UserInputState.Cancel then
rightValue = 0
end
updateMovement(inputState)
end
local jumpFunc = function(actionName, inputState, inputObject)
MasterControl:SetIsJumping(inputState == Enum.UserInputState.Begin)
end
-- TODO: remove up and down arrows, these seem unnecessary
ContextActionService:BindActionToInputTypes("forwardMovement", moveForwardFunc, false, Enum.PlayerActions.CharacterForward)
ContextActionService:BindActionToInputTypes("backwardMovement", moveBackwardFunc, false, Enum.PlayerActions.CharacterBackward)
ContextActionService:BindActionToInputTypes("leftMovement", moveLeftFunc, false, Enum.PlayerActions.CharacterLeft)
ContextActionService:BindActionToInputTypes("rightMovement", moveRightFunc, false, Enum.PlayerActions.CharacterRight)
ContextActionService:BindActionToInputTypes("jumpAction", jumpFunc, false, Enum.PlayerActions.CharacterJump)
-- TODO: make sure we check key state before binding to check if key is already down
local function onFocusReleased()
local humanoid = getHumanoid()
if humanoid then
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = Vector3.new(0, 0, 0)
forwardValue, backwardValue, leftValue, rightValue = 0, 0, 0, 0
MasterControl:SetIsJumping(false)
end
end
local function onTextFocusGained(textboxFocused)
MasterControl:SetIsJumping(false)
end
SeatJumpCn = UserInputService.InputBegan:connect(function(inputObject, isProcessed)
if inputObject.KeyCode == Enum.KeyCode.Backspace and not isProcessed then
local humanoid = getHumanoid()
if humanoid and (humanoid.Sit or humanoid.PlatformStand) then
MasterControl:DoJump()
end
end
end)
TextFocusReleasedCn = UserInputService.TextBoxFocusReleased:connect(onFocusReleased)
TextFocusGainedCn = UserInputService.TextBoxFocused:connect(onTextFocusGained)
-- TODO: remove pcall when API is live
WindowFocusReleasedCn = UserInputService.WindowFocusReleased:connect(onFocusReleased)
end
function KeyboardMovement:Disable()
ContextActionService:UnbindAction("forwardMovement")
ContextActionService:UnbindAction("backwardMovement")
ContextActionService:UnbindAction("leftMovement")
ContextActionService:UnbindAction("rightMovement")
ContextActionService:UnbindAction("jumpAction")
if SeatJumpCn then
SeatJumpCn:disconnect()
SeatJumpCn = nil
end
if TextFocusReleasedCn then
TextFocusReleasedCn:disconnect()
TextFocusReleasedCn = nil
end
if TextFocusGainedCn then
TextFocusGainedCn:disconnect()
TextFocusGainedCn = nil
end
if WindowFocusReleasedCn then
WindowFocusReleasedCn:disconnect()
WindowFocusReleasedCn = nil
end
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = Vector3.new(0,0,0)
MasterControl:SetIsJumping(false)
end
return KeyboardMovement
@@ -0,0 +1,228 @@
--[[
// FileName: Thumbpad
// Version 1.0
// Written by: jmargh
// Description: Implements thumbpad controls for touch devices
--]]
local Players = game:GetService('Players')
local UserInputService = game:GetService('UserInputService')
local GuiService = game:GetService('GuiService')
local Thumbpad = {}
local MasterControl = require(script.Parent)
--[[ Script Variables ]]--
while not Players.LocalPlayer do
wait()
end
local LocalPlayer = Players.LocalPlayer
local ThumbpadFrame = nil
local TouchObject = nil
local OnInputEnded = nil -- is defined in Create()
local OnTouchChangedCn = nil
local OnTouchEndedCn = nil
local currentMoveVector = Vector3.new(0,0,0)
--[[ Constants ]]--
local DPAD_SHEET = "rbxasset://textures/ui/DPadSheet.png"
local TOUCH_CONTROL_SHEET = "rbxasset://textures/ui/TouchControlsSheet.png"
--[[ Local Functions ]]--
local function createArrowLabel(name, parent, position, size, rectOffset, rectSize)
local image = Instance.new('ImageLabel')
image.Name = name
image.Image = DPAD_SHEET
image.ImageRectOffset = rectOffset
image.ImageRectSize = rectSize
image.BackgroundTransparency = 1
image.ImageColor3 = Color3.new(190/255, 190/255, 190/255)
image.Size = size
image.Position = position
image.Parent = parent
return image
end
--[[ Public API ]]--
function Thumbpad:Enable()
ThumbpadFrame.Visible = true
end
function Thumbpad:Disable()
ThumbpadFrame.Visible = false
OnInputEnded()
end
function Thumbpad:Create(parentFrame)
if ThumbpadFrame then
ThumbpadFrame:Destroy()
ThumbpadFrame = nil
if OnTouchChangedCn then
OnTouchChangedCn:disconnect()
OnTouchChangedCn = nil
end
if OnTouchEndedCn then
OnTouchEndedCn:disconnect()
OnTouchEndedCn = nil
end
end
local minAxis = math.min(parentFrame.AbsoluteSize.x, parentFrame.AbsoluteSize.y)
local isSmallScreen = minAxis <= 500
local thumbpadSize = isSmallScreen and 70 or 120
local position = isSmallScreen and UDim2.new(0, thumbpadSize * 1.25, 1, -thumbpadSize - 20) or
UDim2.new(0, thumbpadSize/2 - 10, 1, -thumbpadSize * 1.75 - 10)
ThumbpadFrame = Instance.new('Frame')
ThumbpadFrame.Name = "ThumbpadFrame"
ThumbpadFrame.Visible = false
ThumbpadFrame.Active = true
ThumbpadFrame.Size = UDim2.new(0, thumbpadSize + 20, 0, thumbpadSize + 20)
ThumbpadFrame.Position = position
ThumbpadFrame.BackgroundTransparency = 1
local outerImage = Instance.new('ImageLabel')
outerImage.Name = "OuterImage"
outerImage.Image = TOUCH_CONTROL_SHEET
outerImage.ImageRectOffset = Vector2.new(0, 0)
outerImage.ImageRectSize = Vector2.new(220, 220)
outerImage.BackgroundTransparency = 1
outerImage.Size = UDim2.new(0, thumbpadSize, 0, thumbpadSize)
outerImage.Position = UDim2.new(0, 10, 0, 10)
outerImage.Parent = ThumbpadFrame
local smArrowSize = isSmallScreen and UDim2.new(0, 32, 0, 32) or UDim2.new(0, 64, 0, 64)
local lgArrowSize = UDim2.new(0, smArrowSize.X.Offset * 2, 0, smArrowSize.Y.Offset * 2)
local imgRectSize = Vector2.new(110, 110)
local smImgOffset = isSmallScreen and -4 or -9
local lgImgOffset = isSmallScreen and -28 or -55
local dArrow = createArrowLabel("DownArrow", outerImage, UDim2.new(0.5, -smArrowSize.X.Offset/2, 1, lgImgOffset), smArrowSize, Vector2.new(8, 8), imgRectSize)
local uArrow = createArrowLabel("UpArrow", outerImage, UDim2.new(0.5, -smArrowSize.X.Offset/2, 0, smImgOffset), smArrowSize, Vector2.new(8, 266), imgRectSize)
local lArrow = createArrowLabel("LeftArrow", outerImage, UDim2.new(0, smImgOffset, 0.5, -smArrowSize.Y.Offset/2), smArrowSize, Vector2.new(137, 137), imgRectSize)
local rArrow = createArrowLabel("RightArrow", outerImage, UDim2.new(1, lgImgOffset, 0.5, -smArrowSize.Y.Offset/2), smArrowSize, Vector2.new(8, 137), imgRectSize)
local function doTween(guiObject, endSize, endPosition)
guiObject:TweenSizeAndPosition(endSize, endPosition, Enum.EasingDirection.InOut, Enum.EasingStyle.Linear, 0.15, true)
end
local padOrigin = nil
local deadZone = 0.1
local isRight, isLeft, isUp, isDown = false, false, false, false
local vForward = Vector3.new(0, 0, -1)
local vRight = Vector3.new(1, 0, 0)
local function doMove(pos)
MasterControl:AddToPlayerMovement(-currentMoveVector)
local delta = Vector2.new(pos.x, pos.y) - padOrigin
currentMoveVector = delta / (thumbpadSize/2)
-- Scaled Radial Dead Zone
local inputAxisMagnitude = currentMoveVector.magnitude
if inputAxisMagnitude < deadZone then
currentMoveVector = Vector3.new(0, 0, 0)
else
currentMoveVector = currentMoveVector.unit * ((inputAxisMagnitude - deadZone) / (1 - deadZone))
-- catch possible NAN Vector
if currentMoveVector.magnitude == 0 then
currentMoveVector = Vector3.new(0, 0, 0)
else
currentMoveVector = Vector3.new(currentMoveVector.x, 0, currentMoveVector.y).unit
end
end
MasterControl:AddToPlayerMovement(currentMoveVector)
local forwardDot = currentMoveVector:Dot(vForward)
local rightDot = currentMoveVector:Dot(vRight)
if forwardDot > 0.5 then -- UP
if not isUp then
isUp, isDown = true, false
doTween(uArrow, lgArrowSize, UDim2.new(0.5, -smArrowSize.X.Offset, 0, smImgOffset - smArrowSize.Y.Offset * 1.5))
doTween(dArrow, smArrowSize, UDim2.new(0.5, -smArrowSize.X.Offset/2, 1, lgImgOffset))
end
elseif forwardDot < -0.5 then -- DOWN
if not isDown then
isDown, isUp = true, false
doTween(dArrow, lgArrowSize, UDim2.new(0.5, -smArrowSize.X.Offset, 1, lgImgOffset + smArrowSize.Y.Offset/2))
doTween(uArrow, smArrowSize, UDim2.new(0.5, -smArrowSize.X.Offset/2, 0, smImgOffset))
end
else
isUp, isDown = false, false
doTween(dArrow, smArrowSize, UDim2.new(0.5, -smArrowSize.X.Offset/2, 1, lgImgOffset))
doTween(uArrow, smArrowSize, UDim2.new(0.5, -smArrowSize.X.Offset/2, 0, smImgOffset))
end
if rightDot > 0.5 then
if not isRight then
isRight, isLeft = true, false
doTween(rArrow, lgArrowSize, UDim2.new(1, lgImgOffset + smArrowSize.X.Offset/2, 0.5, -smArrowSize.Y.Offset))
doTween(lArrow, smArrowSize, UDim2.new(0, smImgOffset, 0.5, -smArrowSize.Y.Offset/2))
end
elseif rightDot < -0.5 then
if not isLeft then
isLeft, isRight = true, false
doTween(lArrow, lgArrowSize, UDim2.new(0, smImgOffset - smArrowSize.X.Offset * 1.5, 0.5, -smArrowSize.Y.Offset))
doTween(rArrow, smArrowSize, UDim2.new(1, lgImgOffset, 0.5, -smArrowSize.Y.Offset/2))
end
else
isRight, isLeft = false, false
doTween(lArrow, smArrowSize, UDim2.new(0, smImgOffset, 0.5, -smArrowSize.Y.Offset/2))
doTween(rArrow, smArrowSize, UDim2.new(1, lgImgOffset, 0.5, -smArrowSize.Y.Offset/2))
end
end
--input connections
ThumbpadFrame.InputBegan:connect(function(inputObject)
--A touch that starts elsewhere on the screen will be sent to a frame's InputBegan event
--if it moves over the frame. So we check that this is actually a new touch (inputObject.UserInputState ~= Enum.UserInputState.Begin)
if TouchObject or inputObject.UserInputType ~= Enum.UserInputType.Touch
or inputObject.UserInputState ~= Enum.UserInputState.Begin then
return
end
ThumbpadFrame.Position = UDim2.new(0, inputObject.Position.x - ThumbpadFrame.AbsoluteSize.x/2, 0, inputObject.Position.y - ThumbpadFrame.Size.Y.Offset/2)
padOrigin = Vector2.new(ThumbpadFrame.AbsolutePosition.x + ThumbpadFrame.AbsoluteSize.x/2,
ThumbpadFrame.AbsolutePosition.y + ThumbpadFrame.AbsoluteSize.y/2)
doMove(inputObject.Position)
TouchObject = inputObject
end)
OnTouchChangedCn = UserInputService.TouchMoved:connect(function(inputObject, isProcessed)
if inputObject == TouchObject then
doMove(TouchObject.Position)
end
end)
OnInputEnded = function()
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = Vector3.new(0,0,0)
MasterControl:SetIsJumping(false)
ThumbpadFrame.Position = position
TouchObject = nil
isUp, isDown, isLeft, isRight = false, false, false, false
doTween(dArrow, smArrowSize, UDim2.new(0.5, -smArrowSize.X.Offset/2, 1, lgImgOffset))
doTween(uArrow, smArrowSize, UDim2.new(0.5, -smArrowSize.X.Offset/2, 0, smImgOffset))
doTween(lArrow, smArrowSize, UDim2.new(0, smImgOffset, 0.5, -smArrowSize.Y.Offset/2))
doTween(rArrow, smArrowSize, UDim2.new(1, lgImgOffset, 0.5, -smArrowSize.Y.Offset/2))
end
OnTouchEndedCn = UserInputService.TouchEnded:connect(function(inputObject)
if inputObject == TouchObject then
OnInputEnded()
end
end)
GuiService.MenuOpened:connect(function()
if TouchObject then
OnInputEnded()
end
end)
ThumbpadFrame.Parent = parentFrame
end
return Thumbpad
@@ -0,0 +1,178 @@
--[[
// FileName: Thumbstick
// Version 1.0
// Written by: jmargh
// Description: Implements thumbstick controls for touch devices
--]]
local Players = game:GetService('Players')
local UserInputService = game:GetService('UserInputService')
local GuiService = game:GetService('GuiService')
local MasterControl = require(script.Parent)
local Thumbstick = {}
--[[ Script Variables ]]--
while not Players.LocalPlayer do
wait()
end
local LocalPlayer = Players.LocalPlayer
local IsFollowStick = false
local ThumbstickFrame = nil
local MoveTouchObject = nil
local OnTouchEnded = nil -- defined in Create()
local OnTouchMovedCn = nil
local OnTouchEndedCn = nil
local currentMoveVector = Vector3.new(0,0,0)
--[[ Constants ]]--
local TOUCH_CONTROL_SHEET = "rbxasset://textures/ui/TouchControlsSheet.png"
--[[ Public API ]]--
function Thumbstick:Enable()
ThumbstickFrame.Visible = true
end
function Thumbstick:Disable()
ThumbstickFrame.Visible = false
OnTouchEnded()
end
function Thumbstick:Create(parentFrame)
if ThumbstickFrame then
ThumbstickFrame:Destroy()
ThumbstickFrame = nil
if OnTouchMovedCn then
OnTouchMovedCn:disconnect()
OnTouchMovedCn = nil
end
if OnTouchEndedCn then
OnTouchEndedCn:disconnect()
OnTouchEndedCn = nil
end
end
local minAxis = math.min(parentFrame.AbsoluteSize.x, parentFrame.AbsoluteSize.y)
local isSmallScreen = minAxis <= 500
local thumbstickSize = isSmallScreen and 70 or 120
local position = isSmallScreen and UDim2.new(0, (thumbstickSize/2) - 10, 1, -thumbstickSize - 20) or
UDim2.new(0, thumbstickSize/2, 1, -thumbstickSize * 1.75)
ThumbstickFrame = Instance.new('Frame')
ThumbstickFrame.Name = "ThumbstickFrame"
ThumbstickFrame.Active = true
ThumbstickFrame.Visible = false
ThumbstickFrame.Size = UDim2.new(0, thumbstickSize, 0, thumbstickSize)
ThumbstickFrame.Position = position
ThumbstickFrame.BackgroundTransparency = 1
local outerImage = Instance.new('ImageLabel')
outerImage.Name = "OuterImage"
outerImage.Image = TOUCH_CONTROL_SHEET
outerImage.ImageRectOffset = Vector2.new()
outerImage.ImageRectSize = Vector2.new(220, 220)
outerImage.BackgroundTransparency = 1
outerImage.Size = UDim2.new(0, thumbstickSize, 0, thumbstickSize)
outerImage.Position = UDim2.new(0, 0, 0, 0)
outerImage.Parent = ThumbstickFrame
StickImage = Instance.new('ImageLabel')
StickImage.Name = "StickImage"
StickImage.Image = TOUCH_CONTROL_SHEET
StickImage.ImageRectOffset = Vector2.new(220, 0)
StickImage.ImageRectSize = Vector2.new(111, 111)
StickImage.BackgroundTransparency = 1
StickImage.Size = UDim2.new(0, thumbstickSize/2, 0, thumbstickSize/2)
StickImage.Position = UDim2.new(0, thumbstickSize/2 - thumbstickSize/4, 0, thumbstickSize/2 - thumbstickSize/4)
StickImage.ZIndex = 2
StickImage.Parent = ThumbstickFrame
local centerPosition = nil
local deadZone = 0.05
local function doMove(direction)
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = direction / (thumbstickSize/2)
-- Scaled Radial Dead Zone
local inputAxisMagnitude = currentMoveVector.magnitude
if inputAxisMagnitude < deadZone then
currentMoveVector = Vector3.new()
else
currentMoveVector = currentMoveVector.unit * ((inputAxisMagnitude - deadZone) / (1 - deadZone))
-- NOTE: Making currentMoveVector a unit vector will cause the player to instantly go max speed
-- must check for zero length vector is using unit
currentMoveVector = Vector3.new(currentMoveVector.x, 0, currentMoveVector.y)
end
MasterControl:AddToPlayerMovement(currentMoveVector)
end
local function moveStick(pos)
local relativePosition = Vector2.new(pos.x - centerPosition.x, pos.y - centerPosition.y)
local length = relativePosition.magnitude
local maxLength = ThumbstickFrame.AbsoluteSize.x/2
if IsFollowStick and length > maxLength then
local offset = relativePosition.unit * maxLength
ThumbstickFrame.Position = UDim2.new(
0, pos.x - ThumbstickFrame.AbsoluteSize.x/2 - offset.x,
0, pos.y - ThumbstickFrame.AbsoluteSize.y/2 - offset.y)
else
length = math.min(length, maxLength)
relativePosition = relativePosition.unit * length
end
StickImage.Position = UDim2.new(0, relativePosition.x + StickImage.AbsoluteSize.x/2, 0, relativePosition.y + StickImage.AbsoluteSize.y/2)
end
-- input connections
ThumbstickFrame.InputBegan:connect(function(inputObject)
--A touch that starts elsewhere on the screen will be sent to a frame's InputBegan event
--if it moves over the frame. So we check that this is actually a new touch (inputObject.UserInputState ~= Enum.UserInputState.Begin)
if MoveTouchObject or inputObject.UserInputType ~= Enum.UserInputType.Touch
or inputObject.UserInputState ~= Enum.UserInputState.Begin then
return
end
MoveTouchObject = inputObject
ThumbstickFrame.Position = UDim2.new(0, inputObject.Position.x - ThumbstickFrame.Size.X.Offset/2, 0, inputObject.Position.y - ThumbstickFrame.Size.Y.Offset/2)
centerPosition = Vector2.new(ThumbstickFrame.AbsolutePosition.x + ThumbstickFrame.AbsoluteSize.x/2,
ThumbstickFrame.AbsolutePosition.y + ThumbstickFrame.AbsoluteSize.y/2)
local direction = Vector2.new(inputObject.Position.x - centerPosition.x, inputObject.Position.y - centerPosition.y)
end)
OnTouchMovedCn = UserInputService.TouchMoved:connect(function(inputObject, isProcessed)
if inputObject == MoveTouchObject then
centerPosition = Vector2.new(ThumbstickFrame.AbsolutePosition.x + ThumbstickFrame.AbsoluteSize.x/2,
ThumbstickFrame.AbsolutePosition.y + ThumbstickFrame.AbsoluteSize.y/2)
local direction = Vector2.new(inputObject.Position.x - centerPosition.x, inputObject.Position.y - centerPosition.y)
doMove(direction)
moveStick(inputObject.Position)
end
end)
OnTouchEnded = function()
ThumbstickFrame.Position = position
StickImage.Position = UDim2.new(0, ThumbstickFrame.Size.X.Offset/2 - thumbstickSize/4, 0, ThumbstickFrame.Size.Y.Offset/2 - thumbstickSize/4)
MoveTouchObject = nil
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = Vector3.new(0,0,0)
MasterControl:SetIsJumping(false)
end
OnTouchEndedCn = UserInputService.TouchEnded:connect(function(inputObject, isProcessed)
if inputObject == MoveTouchObject then
OnTouchEnded()
end
end)
GuiService.MenuOpened:connect(function()
if MoveTouchObject then
OnTouchEnded()
end
end)
ThumbstickFrame.Parent = parentFrame
end
return Thumbstick
@@ -0,0 +1,172 @@
--[[
// FileName: TouchJump
// Version 1.0
// Written by: jmargh
// Description: Implements jump controls for touch devices. Use with Thumbstick and Thumbpad
--]]
local Players = game:GetService('Players')
local GuiService = game:GetService('GuiService')
local TouchJump = {}
local MasterControl = require(script.Parent)
--[[ Script Variables ]]--
while not Players.LocalPlayer do
wait()
end
local LocalPlayer = Players.LocalPlayer
local Humanoid = MasterControl:GetHumanoid()
local JumpButton = nil
local OnInputEnded = nil -- defined in Create()
local CharacterAddedConnection = nil
local HumStateConnection = nil
local HumChangeConnection = nil
local ExternallyEnabled = false
local JumpPower = 0
local JumpStateEnabled = true
--[[ Constants ]]--
local TOUCH_CONTROL_SHEET = "rbxasset://textures/ui/Input/TouchControlsSheetV2.png"
--[[ Private Functions ]]--
local function disableButton()
JumpButton.Visible = false
OnInputEnded()
end
local function enableButton()
if Humanoid and ExternallyEnabled then
if ExternallyEnabled then
if Humanoid.JumpPower > 0 then
JumpButton.Visible = true
end
end
end
end
local function updateEnabled()
if JumpPower > 0 and JumpStateEnabled then
enableButton()
else
disableButton()
end
end
local function humanoidChanged(prop)
if prop == "JumpPower" then
JumpPower = Humanoid.JumpPower
updateEnabled()
elseif prop == "Parent" then
if not Humanoid.Parent then
HumChangeConnection:disconnect()
end
end
end
local function humandoidStateEnabledChanged(state, isEnabled)
if state == Enum.HumanoidStateType.Jumping then
JumpStateEnabled = isEnabled
updateEnabled()
end
end
local function characterAdded(newCharacter)
if HumChangeConnection then
HumChangeConnection:disconnect()
end
-- rebind event to new Humanoid
Humanoid = nil
repeat
Humanoid = MasterControl:GetHumanoid()
wait()
until Humanoid and Humanoid.Parent == newCharacter
HumChangeConnection = Humanoid.Changed:connect(humanoidChanged)
HumStateConnection = Humanoid.StateEnabledChanged:connect(humandoidStateEnabledChanged)
JumpPower = Humanoid.JumpPower
JumpStateEnabled = Humanoid:GetStateEnabled(Enum.HumanoidStateType.Jumping)
updateEnabled()
end
local function setupCharacterAddedFunction()
CharacterAddedConnection = LocalPlayer.CharacterAdded:connect(characterAdded)
if LocalPlayer.Character then
characterAdded(LocalPlayer.Character)
end
end
--[[ Public API ]]--
function TouchJump:Enable()
ExternallyEnabled = true
enableButton()
end
function TouchJump:Disable()
ExternallyEnabled = false
disableButton()
end
function TouchJump:Create(parentFrame)
if JumpButton then
JumpButton:Destroy()
JumpButton = nil
end
local minAxis = math.min(parentFrame.AbsoluteSize.x, parentFrame.AbsoluteSize.y)
local isSmallScreen = minAxis <= 500
local jumpButtonSize = isSmallScreen and 70 or 120
JumpButton = Instance.new('ImageButton')
JumpButton.Name = "JumpButton"
JumpButton.Visible = false
JumpButton.BackgroundTransparency = 1
JumpButton.Image = TOUCH_CONTROL_SHEET
JumpButton.ImageRectOffset = Vector2.new(1, 146)
JumpButton.ImageRectSize = Vector2.new(144, 144)
JumpButton.Size = UDim2.new(0, jumpButtonSize, 0, jumpButtonSize)
JumpButton.Position = isSmallScreen and UDim2.new(1, -(jumpButtonSize*1.5-10), 1, -jumpButtonSize - 20) or
UDim2.new(1, -(jumpButtonSize*1.5-10), 1, -jumpButtonSize * 1.75)
local touchObject = nil
JumpButton.InputBegan:connect(function(inputObject)
--A touch that starts elsewhere on the screen will be sent to a frame's InputBegan event
--if it moves over the frame. So we check that this is actually a new touch (inputObject.UserInputState ~= Enum.UserInputState.Begin)
if touchObject or inputObject.UserInputType ~= Enum.UserInputType.Touch
or inputObject.UserInputState ~= Enum.UserInputState.Begin then
return
end
touchObject = inputObject
JumpButton.ImageRectOffset = Vector2.new(146, 146)
MasterControl:SetIsJumping(true)
end)
OnInputEnded = function()
touchObject = nil
MasterControl:SetIsJumping(false)
JumpButton.ImageRectOffset = Vector2.new(1, 146)
end
JumpButton.InputEnded:connect(function(inputObject)
if inputObject == touchObject then
OnInputEnded()
end
end)
GuiService.MenuOpened:connect(function()
if touchObject then
OnInputEnded()
end
end)
if not CharacterAddedConnection then
setupCharacterAddedFunction()
end
JumpButton.Parent = parentFrame
end
return TouchJump
@@ -0,0 +1,433 @@
local VRService = game:GetService("VRService")
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local PathfindingService = game:GetService("PathfindingService")
local ContextActionService = game:GetService("ContextActionService")
local StarterGui = game:GetService("StarterGui")
local MasterControl = require(script.Parent)
local PathDisplay = nil
local LocalPlayer = Players.LocalPlayer
local VRNavigation = {}
local RECALCULATE_PATH_THRESHOLD = 4
local NO_PATH_THRESHOLD = 12
local MAX_PATHING_DISTANCE = 200
local POINT_REACHED_THRESHOLD = 1
local STOPPING_DISTANCE = 4
local OFFTRACK_TIME_THRESHOLD = 2
local ZERO_VECTOR3 = Vector3.new(0, 0, 0)
local XZ_VECTOR3 = Vector3.new(1, 0, 1)
local THUMBSTICK_DEADZONE = 0.22
local navigationRequestedConn = nil
local heartbeatConn = nil
local currentDestination = nil
local currentPath = nil
local currentPoints = nil
local currentPointIdx = 0
local currentMoveVector = Vector3.new(0, 0, 0)
local expectedTimeToNextPoint = 0
local timeReachedLastPoint = tick()
local movementUpdateEvent = Instance.new("BindableEvent")
movementUpdateEvent.Name = "MovementUpdate"
movementUpdateEvent.Parent = script
coroutine.wrap(function()
local PathDisplayModule = script.Parent.Parent:WaitForChild("PathDisplay")
if PathDisplayModule then
PathDisplay = require(PathDisplayModule)
end
end)()
local function setLaserPointerMode(mode)
pcall(function()
StarterGui:SetCore("VRLaserPointerMode", mode)
end)
end
local function getLocalHumanoid()
local character = LocalPlayer.Character
if not character then
return
end
for _, child in pairs(character:GetChildren()) do
if child:IsA("Humanoid") then
return child
end
end
return nil
end
local function hasBothHandControllers()
return VRService:GetUserCFrameEnabled(Enum.UserCFrame.RightHand) and VRService:GetUserCFrameEnabled(Enum.UserCFrame.LeftHand)
end
local function hasAnyHandControllers()
return VRService:GetUserCFrameEnabled(Enum.UserCFrame.RightHand) or VRService:GetUserCFrameEnabled(Enum.UserCFrame.LeftHand)
end
local function isMobileVR()
return UserInputService.TouchEnabled
end
local function hasGamepad()
return UserInputService.GamepadEnabled
end
local function shouldUseNavigationLaser()
--Places where we use the navigation laser:
-- mobile VR with any number of hands tracked
-- desktop VR with only one hand tracked
-- desktop VR with no hands and no gamepad (i.e. with Oculus remote?)
--using an Xbox controller with a desktop VR headset means no laser since the user has a thumbstick.
--in the future, we should query thumbstick presence with a features API
if isMobileVR() then
return true
else
if hasBothHandControllers() then
return false
end
if not hasAnyHandControllers() then
return not hasGamepad()
end
return true
end
end
local function IsFinite(num)
return num == num and num ~= 1/0 and num ~= -1/0
end
local function IsFiniteVector3(vec3)
return IsFinite(vec3.x) and IsFinite(vec3.y) and IsFinite(vec3.z)
end
local moving = false
local function startFollowingPath(newPath)
currentPath = newPath
currentPoints = currentPath:GetPointCoordinates()
currentPointIdx = 1
moving = true
timeReachedLastPoint = tick()
local humanoid = getLocalHumanoid()
if humanoid and humanoid.Torso and #currentPoints >= 1 then
local dist = (currentPoints[1] - humanoid.Torso.Position).magnitude
expectedTimeToNextPoint = dist / humanoid.WalkSpeed
end
movementUpdateEvent:Fire("targetPoint", currentDestination)
end
local function goToPoint(point)
currentPath = true
currentPoints = { point }
currentPointIdx = 1
moving = true
local humanoid = getLocalHumanoid()
local distance = (humanoid.Torso.Position - point).magnitude
local estimatedTimeRemaining = distance / humanoid.WalkSpeed
timeReachedLastPoint = tick()
expectedTimeToNextPoint = estimatedTimeRemaining
movementUpdateEvent:Fire("targetPoint", point)
end
local function stopFollowingPath()
currentPath = nil
currentPoints = nil
currentPointIdx = 0
moving = false
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = ZERO_VECTOR3
end
local function tryComputePath(startPos, destination)
local numAttempts = 0
local newPath = nil
while not newPath and numAttempts < 5 do
newPath = PathfindingService:ComputeSmoothPathAsync(startPos, destination, MAX_PATHING_DISTANCE)
numAttempts = numAttempts + 1
if newPath.Status == Enum.PathStatus.ClosestNoPath or newPath.Status == Enum.PathStatus.ClosestOutOfRange then
newPath = nil
break
end
if newPath and newPath.Status == Enum.PathStatus.FailStartNotEmpty then
startPos = startPos + (destination - startPos).unit
newPath = nil
end
if newPath and newPath.Status == Enum.PathStatus.FailFinishNotEmpty then
destination = destination + Vector3.new(0, 1, 0)
newPath = nil
end
end
return newPath
end
local function onNavigationRequest(destinationCFrame, requestedWith)
local destinationPosition = destinationCFrame.p
local lastDestination = currentDestination
if not IsFiniteVector3(destinationPosition) then
return
end
currentDestination = destinationPosition
local humanoid = getLocalHumanoid()
if not humanoid or not humanoid.Torso then
return
end
local currentPosition = humanoid.Torso.Position
local distanceToDestination = (currentDestination - currentPosition).magnitude
if distanceToDestination < NO_PATH_THRESHOLD then
goToPoint(currentDestination)
return
end
if not lastDestination or (currentDestination - lastDestination).magnitude > RECALCULATE_PATH_THRESHOLD then
local newPath = tryComputePath(currentPosition, currentDestination)
if newPath then
startFollowingPath(newPath)
if PathDisplay then
PathDisplay.setCurrentPoints(currentPoints)
PathDisplay.renderPath()
end
else
stopFollowingPath()
if PathDisplay then
PathDisplay.clearRenderedPath()
end
end
else
if moving then
currentPoints[#currentPoints] = currentDestination
else
goToPoint(currentDestination)
end
end
end
local isJumpBound = false
local function onJumpAction(actionName, inputState, inputObj)
if inputState == Enum.UserInputState.Begin then
MasterControl:DoJump()
end
end
local function bindJumpAction(active)
if active then
if not isJumpBound then
isJumpBound = true
ContextActionService:BindAction("VRJumpAction", onJumpAction, false, Enum.KeyCode.ButtonA)
end
else
if isJumpBound then
isJumpBound = false
ContextActionService:UnbindAction("VRJumpAction")
end
end
end
local moveLatch = false
local controlCharacterGamepad = function(actionName, inputState, inputObject)
if inputObject.KeyCode ~= Enum.KeyCode.Thumbstick1 then return end
if inputState == Enum.UserInputState.Cancel then
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = Vector3.new(0,0,0)
return
end
if inputState ~= Enum.UserInputState.End then
stopFollowingPath()
if PathDisplay then
PathDisplay.clearRenderedPath()
end
if shouldUseNavigationLaser() then
bindJumpAction(true)
setLaserPointerMode("Hidden")
end
if inputObject.Position.magnitude > THUMBSTICK_DEADZONE then
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = Vector3.new(inputObject.Position.X, 0, -inputObject.Position.Y)
if currentMoveVector.magnitude > 0 then
currentMoveVector = currentMoveVector.unit * math.min(1, inputObject.Position.magnitude)
end
MasterControl:AddToPlayerMovement(currentMoveVector)
moveLatch = true
end
else
MasterControl:AddToPlayerMovement(-currentMoveVector)
currentMoveVector = Vector3.new(0,0,0)
if shouldUseNavigationLaser() then
bindJumpAction(false)
setLaserPointerMode("Navigation")
end
if moveLatch then
moveLatch = false
movementUpdateEvent:Fire("offtrack")
end
end
end
local function onHeartbeat(dt)
local newMoveVector = currentMoveVector
local humanoid = getLocalHumanoid()
if not humanoid or not humanoid.Torso then
return
end
if moving and currentPoints then
local currentPosition = humanoid.Torso.Position
local goalPosition = currentPoints[1]
local vectorToGoal = (goalPosition - currentPosition) * XZ_VECTOR3
local moveDist = vectorToGoal.magnitude
local moveDir = vectorToGoal / moveDist
if moveDist < POINT_REACHED_THRESHOLD then
local estimatedTimeRemaining = 0
local prevPoint = currentPoints[1]
for i, point in pairs(currentPoints) do
if i ~= 1 then
local dist = (point - prevPoint).magnitude
prevPoint = point
estimatedTimeRemaining = estimatedTimeRemaining + (dist / humanoid.WalkSpeed)
end
end
table.remove(currentPoints, 1)
currentPointIdx = currentPointIdx + 1
if #currentPoints == 0 then
stopFollowingPath()
if PathDisplay then
PathDisplay.clearRenderedPath()
end
return
else
if PathDisplay then
PathDisplay.setCurrentPoints(currentPoints)
PathDisplay.renderPath()
end
local newGoal = currentPoints[1]
local distanceToGoal = (newGoal - currentPosition).magnitude
expectedTimeToNextPoint = distanceToGoal / humanoid.WalkSpeed
timeReachedLastPoint = tick()
end
else
local ignoreTable = {
game.Players.LocalPlayer.Character,
workspace.CurrentCamera
}
local obstructRay = Ray.new(currentPosition - Vector3.new(0, 1, 0), moveDir * 3)
local obstructPart, obstructPoint, obstructNormal = workspace:FindPartOnRayWithIgnoreList(obstructRay, ignoreTable)
if obstructPart then
local heightOffset = Vector3.new(0, 100, 0)
local jumpCheckRay = Ray.new(obstructPoint + moveDir * 0.5 + heightOffset, -heightOffset)
local jumpCheckPart, jumpCheckPoint, jumpCheckNormal = workspace:FindPartOnRayWithIgnoreList(jumpCheckRay, ignoreTable)
local heightDifference = jumpCheckPoint.Y - currentPosition.Y
if heightDifference < 6 and heightDifference > -2 then
humanoid.Jump = true
end
end
local timeSinceLastPoint = tick() - timeReachedLastPoint
if timeSinceLastPoint > expectedTimeToNextPoint + OFFTRACK_TIME_THRESHOLD then
stopFollowingPath()
if PathDisplay then
PathDisplay.clearRenderedPath()
end
movementUpdateEvent:Fire("offtrack")
end
newMoveVector = currentMoveVector:Lerp(moveDir, dt * 10)
end
end
if IsFiniteVector3(newMoveVector) then
MasterControl:AddToPlayerMovement(newMoveVector - currentMoveVector)
currentMoveVector = newMoveVector
end
end
local userCFrameEnabledConn = nil
local function onUserCFrameEnabled()
if shouldUseNavigationLaser() then
bindJumpAction(false)
setLaserPointerMode("Navigation")
else
bindJumpAction(true)
setLaserPointerMode("Hidden")
end
end
function VRNavigation:Enable()
navigationRequestedConn = VRService.NavigationRequested:connect(onNavigationRequest)
heartbeatConn = RunService.Heartbeat:connect(onHeartbeat)
ContextActionService:BindAction("MoveThumbstick", controlCharacterGamepad, false, Enum.KeyCode.Thumbstick1)
ContextActionService:BindActivate(Enum.UserInputType.Gamepad1, Enum.KeyCode.ButtonR2)
userCFrameEnabledConn = VRService.UserCFrameEnabled:connect(onUserCFrameEnabled)
onUserCFrameEnabled()
pcall(function()
VRService:SetTouchpadMode(Enum.VRTouchpad.Left, Enum.VRTouchpadMode.VirtualThumbstick)
VRService:SetTouchpadMode(Enum.VRTouchpad.Right, Enum.VRTouchpadMode.ABXY)
end)
end
function VRNavigation:Disable()
stopFollowingPath()
ContextActionService:UnbindAction("MoveThumbstick")
ContextActionService:UnbindActivate(Enum.UserInputType.Gamepad1, Enum.KeyCode.ButtonR2)
bindJumpAction(false)
setLaserPointerMode("Disabled")
if navigationRequestedConn then
navigationRequestedConn:disconnect()
navigationRequestedConn = nil
end
if heartbeatConn then
heartbeatConn:disconnect()
heartbeatConn = nil
end
if userCFrameEnabledConn then
userCFrameEnabledConn:disconnect()
userCFrameEnabledConn = nil
end
end
return VRNavigation
@@ -0,0 +1,180 @@
--[[
// FileName: VehicleControl
// Version 1.0
// Written by: jmargh
// Description: Implements in-game vehicle controls for all input devices
// NOTE: This works for basic vehicles (single vehicle seat). If you use custom VehicleSeat code,
// multiple VehicleSeats or your own implementation of a VehicleSeat this will not work.
--]]
local VehicleController = {}
local ContextActionService = game:GetService('ContextActionService')
local Players = game:GetService('Players')
local RunService = game:GetService('RunService')
local MasterControl = require(script.Parent)
while not Players.LocalPlayer do
wait()
end
local LocalPlayer = Players.LocalPlayer
local CurrentVehicleSeat = nil
local CurrentThrottle = 0
local CurrentSteer = 0
local HumanoidSeatedCn = nil
local RenderSteppedCn = nil
local Accelerating = false
local Deccelerating = false
local TurningRight = false
local TurningLeft = false
-- Set this to true if you want to instead use the triggers for the throttle
local useTriggersForThrottle = true
-- Also set this to true if you want the thumbstick to not affect throttle, only triggers when a gamepad is conected
local onlyTriggersForThrottle = false
local function onThrottleAccel(actionName, inputState, inputObject)
MasterControl:AddToPlayerMovement(Vector3.new(0, 0, -CurrentThrottle))
CurrentThrottle = (inputState == Enum.UserInputState.End or Deccelerating) and 0 or -1
MasterControl:AddToPlayerMovement(Vector3.new(0, 0, CurrentThrottle))
Accelerating = not (inputState == Enum.UserInputState.End)
if (inputState == Enum.UserInputState.End) and Deccelerating then
CurrentThrottle = 1
MasterControl:AddToPlayerMovement(Vector3.new(0, 0, CurrentThrottle))
end
end
local function onThrottleDeccel(actionName, inputState, inputObject)
MasterControl:AddToPlayerMovement(Vector3.new(0, 0, -CurrentThrottle))
CurrentThrottle = (inputState == Enum.UserInputState.End or Accelerating) and 0 or 1
MasterControl:AddToPlayerMovement(Vector3.new(0, 0, CurrentThrottle))
Deccelerating = not (inputState == Enum.UserInputState.End)
if (inputState == Enum.UserInputState.End) and Accelerating then
CurrentThrottle = -1
MasterControl:AddToPlayerMovement(Vector3.new(0, 0, CurrentThrottle))
end
end
local function onSteerRight(actionName, inputState, inputObject)
MasterControl:AddToPlayerMovement(Vector3.new(-CurrentSteer, 0, 0))
CurrentSteer = (inputState == Enum.UserInputState.End or TurningLeft) and 0 or 1
MasterControl:AddToPlayerMovement(Vector3.new(CurrentSteer, 0, 0))
TurningRight = not (inputState == Enum.UserInputState.End)
if (inputState == Enum.UserInputState.End) and TurningLeft then
CurrentSteer = -1
MasterControl:AddToPlayerMovement(Vector3.new(CurrentSteer, 0, 0))
end
end
local function onSteerLeft(actionName, inputState, inputObject)
MasterControl:AddToPlayerMovement(Vector3.new(-CurrentSteer, 0, 0))
CurrentSteer = (inputState == Enum.UserInputState.End or TurningRight) and 0 or -1
MasterControl:AddToPlayerMovement(Vector3.new(CurrentSteer, 0, 0))
TurningLeft = not (inputState == Enum.UserInputState.End)
if (inputState == Enum.UserInputState.End) and TurningRight then
CurrentSteer = 1
MasterControl:AddToPlayerMovement(Vector3.new(CurrentSteer, 0, 0))
end
end
local function getHumanoid()
local character = LocalPlayer and LocalPlayer.Character
if character then
for _,child in pairs(character:GetChildren()) do
if child:IsA('Humanoid') then
return child
end
end
end
end
local function getClosestFittingValue(value)
if value > 0.5 then
return 1
elseif value < -0.5 then
return -1
end
return 0
end
local function onRenderStepped()
if CurrentVehicleSeat then
local moveValue = MasterControl:GetMoveVector()
local didSetThrottleSteerFloat = false
didSetThrottleSteerFloat = pcall(function()
if game:GetService("UserInputService"):GetGamepadConnected(Enum.UserInputType.Gamepad1) and onlyTriggersForThrottle and useTriggersForThrottle then
CurrentVehicleSeat.ThrottleFloat = -CurrentThrottle
else
CurrentVehicleSeat.ThrottleFloat = -moveValue.z
end
CurrentVehicleSeat.SteerFloat = moveValue.x
end)
if didSetThrottleSteerFloat == false then
if game:GetService("UserInputService"):GetGamepadConnected(Enum.UserInputType.Gamepad1) and onlyTriggersForThrottle and useTriggersForThrottle then
CurrentVehicleSeat.Throttle = -CurrentThrottle
else
CurrentVehicleSeat.Throttle = getClosestFittingValue(-moveValue.z)
end
CurrentVehicleSeat.Steer = getClosestFittingValue(moveValue.x)
end
end
end
local function onSeated(active, currentSeatPart)
if active then
if currentSeatPart and currentSeatPart:IsA('VehicleSeat') then
CurrentVehicleSeat = currentSeatPart
if useTriggersForThrottle then
ContextActionService:BindAction("throttleAccel", onThrottleAccel, false, Enum.KeyCode.ButtonR2)
ContextActionService:BindAction("throttleDeccel", onThrottleDeccel, false, Enum.KeyCode.ButtonL2)
end
ContextActionService:BindAction("arrowSteerRight", onSteerRight, false, Enum.KeyCode.Right)
ContextActionService:BindAction("arrowSteerLeft", onSteerLeft, false, Enum.KeyCode.Left)
local success = pcall(function() RunService:BindToRenderStep("VehicleControlStep", Enum.RenderPriority.Input.Value, onRenderStepped) end)
if not success then
if RenderSteppedCn then return end
RenderSteppedCn = RunService.RenderStepped:connect(onRenderStepped)
end
end
else
CurrentVehicleSeat = nil
if useTriggersForThrottle then
ContextActionService:UnbindAction("throttleAccel")
ContextActionService:UnbindAction("throttleDeccel")
end
ContextActionService:UnbindAction("arrowSteerRight")
ContextActionService:UnbindAction("arrowSteerLeft")
MasterControl:AddToPlayerMovement(Vector3.new(-CurrentSteer, 0, -CurrentThrottle))
CurrentThrottle = 0
CurrentSteer = 0
local success = pcall(function() RunService:UnbindFromRenderStep("VehicleControlStep") end)
if not success and RenderSteppedCn then
RenderSteppedCn:disconnect()
RenderSteppedCn = nil
end
end
end
local function CharacterAdded(character)
local humanoid = getHumanoid()
while not humanoid do
wait()
humanoid = getHumanoid()
end
--
if HumanoidSeatedCn then
HumanoidSeatedCn:disconnect()
HumanoidSeatedCn = nil
end
HumanoidSeatedCn = humanoid.Seated:connect(onSeated)
end
if LocalPlayer.Character then
CharacterAdded(LocalPlayer.Character)
end
LocalPlayer.CharacterAdded:connect(CharacterAdded)
return VehicleController
@@ -0,0 +1,131 @@
local PathDisplay = {}
PathDisplay.spacing = 8
PathDisplay.image = "rbxasset://textures/Cursors/Gamepad/Pointer.png"
PathDisplay.imageSize = Vector2.new(2, 2)
local currentPoints = {}
local renderedPoints = {}
local pointModel = Instance.new("Model")
pointModel.Name = "PathDisplayPoints"
local adorneePart = Instance.new("Part")
adorneePart.Anchored = true
adorneePart.CanCollide = false
adorneePart.Transparency = 1
adorneePart.Name = "PathDisplayAdornee"
adorneePart.CFrame = CFrame.new(0, 0, 0)
adorneePart.Parent = pointModel
local pointPool = {}
local poolTop = 30
for i = 1, poolTop do
local point = Instance.new("ImageHandleAdornment")
point.Archivable = false
point.Adornee = adorneePart
point.Image = PathDisplay.image
point.Size = PathDisplay.imageSize
pointPool[i] = point
end
local function retrieveFromPool()
local point = pointPool[1]
if not point then
return
end
pointPool[1], pointPool[poolTop] = pointPool[poolTop], nil
poolTop = poolTop - 1
return point
end
local function returnToPool(point)
poolTop = poolTop + 1
pointPool[poolTop] = point
end
local function renderPoint(point, isLast)
if poolTop == 0 then
return
end
local rayDown = Ray.new(point + Vector3.new(0, 2, 0), Vector3.new(0, -8, 0))
local hitPart, hitPoint, hitNormal = workspace:FindPartOnRayWithIgnoreList(rayDown, { game.Players.LocalPlayer.Character, workspace.CurrentCamera })
if not hitPart then
return
end
local pointCFrame = CFrame.new(hitPoint, hitPoint + hitNormal)
local point = retrieveFromPool()
point.CFrame = pointCFrame
point.Parent = pointModel
return point
end
function PathDisplay.setCurrentPoints(points)
if typeof(points) == 'table' then
currentPoints = points
else
currentPoints = {}
end
end
function PathDisplay.clearRenderedPath()
for _, oldPoint in ipairs(renderedPoints) do
oldPoint.Parent = nil
returnToPool(oldPoint)
end
renderedPoints = {}
pointModel.Parent = nil
end
function PathDisplay.renderPath()
PathDisplay.clearRenderedPath()
if not currentPoints or #currentPoints == 0 then
return
end
local currentIdx = #currentPoints
local lastPos = currentPoints[currentIdx]
local distanceBudget = 0
renderedPoints[1] = renderPoint(lastPos, true)
if not renderedPoints[1] then
return
end
while true do
local currentPoint = currentPoints[currentIdx]
local nextPoint = currentPoints[currentIdx - 1]
if currentIdx < 2 then
break
else
local toNextPoint = nextPoint - currentPoint
local distToNextPoint = toNextPoint.magnitude
if distanceBudget > distToNextPoint then
distanceBudget = distanceBudget - distToNextPoint
currentIdx = currentIdx - 1
else
local dirToNextPoint = toNextPoint.unit
local pointPos = currentPoint + (dirToNextPoint * distanceBudget)
local point = renderPoint(pointPos, false)
if point then
renderedPoints[#renderedPoints + 1] = point
end
distanceBudget = distanceBudget + PathDisplay.spacing
end
end
end
pointModel.Parent = workspace.CurrentCamera
end
return PathDisplay