-
Notifications
You must be signed in to change notification settings - Fork 4
/
Gravity Control
11555 lines (9664 loc) · 362 KB
/
Gravity Control
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[[
local _p = game:WaitForChild("Players")
local _plr = _p.ChildAdded:Wait()
if _plr == _p.LocalPlayer then
_plr.ChildAdded:Connect(function(cccc)
if c.Name == "PlayerScriptsLoader" then
c.Disabled = true
end
end)
end
]]
repeat wait()
a = pcall(function()
game:WaitForChild("Players").LocalPlayer:WaitForChild("PlayerScripts").ChildAdded:Connect(function(c)
if c.Name == "PlayerScriptsLoader"then
c.Disabled = true
end
end)
end)
if a == true then break end
until true == false
game:WaitForChild("Players").LocalPlayer:WaitForChild("PlayerScripts").ChildAdded:Connect(function(c)
if c.Name == "PlayerScriptsLoader"then
c.Disabled = true
end
end)
function _CameraUI()
local Players = game:GetService("Players")
local TweenService = game:GetService("TweenService")
local LocalPlayer = Players.LocalPlayer
if not LocalPlayer then
Players:GetPropertyChangedSignal("LocalPlayer"):Wait()
LocalPlayer = Players.LocalPlayer
end
local function waitForChildOfClass(parent, class)
local child = parent:FindFirstChildOfClass(class)
while not child or child.ClassName ~= class do
child = parent.ChildAdded:Wait()
end
return child
end
local PlayerGui = waitForChildOfClass(LocalPlayer, "PlayerGui")
local TOAST_OPEN_SIZE = UDim2.new(0, 326, 0, 58)
local TOAST_CLOSED_SIZE = UDim2.new(0, 80, 0, 58)
local TOAST_BACKGROUND_COLOR = Color3.fromRGB(32, 32, 32)
local TOAST_BACKGROUND_TRANS = 0.4
local TOAST_FOREGROUND_COLOR = Color3.fromRGB(200, 200, 200)
local TOAST_FOREGROUND_TRANS = 0
-- Convenient syntax for creating a tree of instanes
local function create(className)
return function(props)
local inst = Instance.new(className)
local parent = props.Parent
props.Parent = nil
for name, val in pairs(props) do
if type(name) == "string" then
inst[name] = val
else
val.Parent = inst
end
end
-- Only set parent after all other properties are initialized
inst.Parent = parent
return inst
end
end
local initialized = false
local uiRoot
local toast
local toastIcon
local toastUpperText
local toastLowerText
local function initializeUI()
assert(not initialized)
uiRoot = create("ScreenGui"){
Name = "RbxCameraUI",
AutoLocalize = false,
Enabled = true,
DisplayOrder = -1, -- Appears behind default developer UI
IgnoreGuiInset = false,
ResetOnSpawn = false,
ZIndexBehavior = Enum.ZIndexBehavior.Sibling,
create("ImageLabel"){
Name = "Toast",
Visible = false,
AnchorPoint = Vector2.new(0.5, 0),
BackgroundTransparency = 1,
BorderSizePixel = 0,
Position = UDim2.new(0.5, 0, 0, 8),
Size = TOAST_CLOSED_SIZE,
Image = "rbxasset://textures/ui/Camera/CameraToast9Slice.png",
ImageColor3 = TOAST_BACKGROUND_COLOR,
ImageRectSize = Vector2.new(6, 6),
ImageTransparency = 1,
ScaleType = Enum.ScaleType.Slice,
SliceCenter = Rect.new(3, 3, 3, 3),
ClipsDescendants = true,
create("Frame"){
Name = "IconBuffer",
BackgroundTransparency = 1,
BorderSizePixel = 0,
Position = UDim2.new(0, 0, 0, 0),
Size = UDim2.new(0, 80, 1, 0),
create("ImageLabel"){
Name = "Icon",
AnchorPoint = Vector2.new(0.5, 0.5),
BackgroundTransparency = 1,
Position = UDim2.new(0.5, 0, 0.5, 0),
Size = UDim2.new(0, 48, 0, 48),
ZIndex = 2,
Image = "rbxasset://textures/ui/Camera/CameraToastIcon.png",
ImageColor3 = TOAST_FOREGROUND_COLOR,
ImageTransparency = 1,
}
},
create("Frame"){
Name = "TextBuffer",
BackgroundTransparency = 1,
BorderSizePixel = 0,
Position = UDim2.new(0, 80, 0, 0),
Size = UDim2.new(1, -80, 1, 0),
ClipsDescendants = true,
create("TextLabel"){
Name = "Upper",
AnchorPoint = Vector2.new(0, 1),
BackgroundTransparency = 1,
Position = UDim2.new(0, 0, 0.5, 0),
Size = UDim2.new(1, 0, 0, 19),
Font = Enum.Font.GothamSemibold,
Text = "Camera control enabled",
TextColor3 = TOAST_FOREGROUND_COLOR,
TextTransparency = 1,
TextSize = 19,
TextXAlignment = Enum.TextXAlignment.Left,
TextYAlignment = Enum.TextYAlignment.Center,
},
create("TextLabel"){
Name = "Lower",
AnchorPoint = Vector2.new(0, 0),
BackgroundTransparency = 1,
Position = UDim2.new(0, 0, 0.5, 3),
Size = UDim2.new(1, 0, 0, 15),
Font = Enum.Font.Gotham,
Text = "Right mouse button to toggle",
TextColor3 = TOAST_FOREGROUND_COLOR,
TextTransparency = 1,
TextSize = 15,
TextXAlignment = Enum.TextXAlignment.Left,
TextYAlignment = Enum.TextYAlignment.Center,
},
},
},
Parent = PlayerGui,
}
toast = uiRoot.Toast
toastIcon = toast.IconBuffer.Icon
toastUpperText = toast.TextBuffer.Upper
toastLowerText = toast.TextBuffer.Lower
initialized = true
end
local CameraUI = {}
do
-- Instantaneously disable the toast or enable for opening later on. Used when switching camera modes.
function CameraUI.setCameraModeToastEnabled(enabled)
if not enabled and not initialized then
return
end
if not initialized then
initializeUI()
end
toast.Visible = enabled
if not enabled then
CameraUI.setCameraModeToastOpen(false)
end
end
local tweenInfo = TweenInfo.new(0.25, Enum.EasingStyle.Quad, Enum.EasingDirection.Out)
-- Tween the toast in or out. Toast must be enabled with setCameraModeToastEnabled.
function CameraUI.setCameraModeToastOpen(open)
assert(initialized)
TweenService:Create(toast, tweenInfo, {
Size = open and TOAST_OPEN_SIZE or TOAST_CLOSED_SIZE,
ImageTransparency = open and TOAST_BACKGROUND_TRANS or 1,
}):Play()
TweenService:Create(toastIcon, tweenInfo, {
ImageTransparency = open and TOAST_FOREGROUND_TRANS or 1,
}):Play()
TweenService:Create(toastUpperText, tweenInfo, {
TextTransparency = open and TOAST_FOREGROUND_TRANS or 1,
}):Play()
TweenService:Create(toastLowerText, tweenInfo, {
TextTransparency = open and TOAST_FOREGROUND_TRANS or 1,
}):Play()
end
end
return CameraUI
end
function _CameraToggleStateController()
local Players = game:GetService("Players")
local UserInputService = game:GetService("UserInputService")
local GameSettings = UserSettings():GetService("UserGameSettings")
local LocalPlayer = Players.LocalPlayer
if not LocalPlayer then
Players:GetPropertyChangedSignal("LocalPlayer"):Wait()
LocalPlayer = Players.LocalPlayer
end
local Mouse = LocalPlayer:GetMouse()
local Input = _CameraInput()
local CameraUI = _CameraUI()
local lastTogglePan = false
local lastTogglePanChange = tick()
local CROSS_MOUSE_ICON = "rbxasset://textures/Cursors/CrossMouseIcon.png"
local lockStateDirty = false
local wasTogglePanOnTheLastTimeYouWentIntoFirstPerson = false
local lastFirstPerson = false
CameraUI.setCameraModeToastEnabled(false)
return function(isFirstPerson)
local togglePan = Input.getTogglePan()
local toastTimeout = 3
if isFirstPerson and togglePan ~= lastTogglePan then
lockStateDirty = true
end
if lastTogglePan ~= togglePan or tick() - lastTogglePanChange > toastTimeout then
local doShow = togglePan and tick() - lastTogglePanChange < toastTimeout
CameraUI.setCameraModeToastOpen(doShow)
if togglePan then
lockStateDirty = false
end
lastTogglePanChange = tick()
lastTogglePan = togglePan
end
if isFirstPerson ~= lastFirstPerson then
if isFirstPerson then
wasTogglePanOnTheLastTimeYouWentIntoFirstPerson = Input.getTogglePan()
Input.setTogglePan(true)
elseif not lockStateDirty then
Input.setTogglePan(wasTogglePanOnTheLastTimeYouWentIntoFirstPerson)
end
end
if isFirstPerson then
if Input.getTogglePan() then
Mouse.Icon = CROSS_MOUSE_ICON
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
--GameSettings.RotationType = Enum.RotationType.CameraRelative
else
Mouse.Icon = ""
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
--GameSettings.RotationType = Enum.RotationType.CameraRelative
end
elseif Input.getTogglePan() then
Mouse.Icon = CROSS_MOUSE_ICON
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
GameSettings.RotationType = Enum.RotationType.MovementRelative
elseif Input.getHoldPan() then
Mouse.Icon = ""
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition
GameSettings.RotationType = Enum.RotationType.MovementRelative
else
Mouse.Icon = ""
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
GameSettings.RotationType = Enum.RotationType.MovementRelative
end
lastFirstPerson = isFirstPerson
end
end
function _CameraInput()
local UserInputService = game:GetService("UserInputService")
local MB_TAP_LENGTH = 0.3 -- length of time for a short mouse button tap to be registered
local rmbDown, rmbUp
do
local rmbDownBindable = Instance.new("BindableEvent")
local rmbUpBindable = Instance.new("BindableEvent")
rmbDown = rmbDownBindable.Event
rmbUp = rmbUpBindable.Event
UserInputService.InputBegan:Connect(function(input, gpe)
if not gpe and input.UserInputType == Enum.UserInputType.MouseButton2 then
rmbDownBindable:Fire()
end
end)
UserInputService.InputEnded:Connect(function(input, gpe)
if input.UserInputType == Enum.UserInputType.MouseButton2 then
rmbUpBindable:Fire()
end
end)
end
local holdPan = false
local togglePan = false
local lastRmbDown = 0 -- tick() timestamp of the last right mouse button down event
local CameraInput = {}
function CameraInput.getHoldPan()
return holdPan
end
function CameraInput.getTogglePan()
return togglePan
end
function CameraInput.getPanning()
return togglePan or holdPan
end
function CameraInput.setTogglePan(value)
togglePan = value
end
local cameraToggleInputEnabled = false
local rmbDownConnection
local rmbUpConnection
function CameraInput.enableCameraToggleInput()
if cameraToggleInputEnabled then
return
end
cameraToggleInputEnabled = true
holdPan = false
togglePan = false
if rmbDownConnection then
rmbDownConnection:Disconnect()
end
if rmbUpConnection then
rmbUpConnection:Disconnect()
end
rmbDownConnection = rmbDown:Connect(function()
holdPan = true
lastRmbDown = tick()
end)
rmbUpConnection = rmbUp:Connect(function()
holdPan = false
if tick() - lastRmbDown < MB_TAP_LENGTH and (togglePan or UserInputService:GetMouseDelta().Magnitude < 2) then
togglePan = not togglePan
end
end)
end
function CameraInput.disableCameraToggleInput()
if not cameraToggleInputEnabled then
return
end
cameraToggleInputEnabled = false
if rmbDownConnection then
rmbDownConnection:Disconnect()
rmbDownConnection = nil
end
if rmbUpConnection then
rmbUpConnection:Disconnect()
rmbUpConnection = nil
end
end
return CameraInput
end
function _BaseCamera()
--[[
BaseCamera - Abstract base class for camera control modules
2018 Camera Update - AllYourBlox
--]]
--[[ Local Constants ]]--
local UNIT_Z = Vector3.new(0,0,1)
local X1_Y0_Z1 = Vector3.new(1,0,1) --Note: not a unit vector, used for projecting onto XZ plane
local THUMBSTICK_DEADZONE = 0.2
local DEFAULT_DISTANCE = 12.5 -- Studs
local PORTRAIT_DEFAULT_DISTANCE = 25 -- Studs
local FIRST_PERSON_DISTANCE_THRESHOLD = 1.0 -- Below this value, snap into first person
local CAMERA_ACTION_PRIORITY = Enum.ContextActionPriority.Default.Value
-- Note: DotProduct check in CoordinateFrame::lookAt() prevents using values within about
-- 8.11 degrees of the +/- Y axis, that's why these limits are currently 80 degrees
local MIN_Y = math.rad(-80)
local MAX_Y = math.rad(80)
local TOUCH_ADJUST_AREA_UP = math.rad(30)
local TOUCH_ADJUST_AREA_DOWN = math.rad(-15)
local TOUCH_SENSITIVTY_ADJUST_MAX_Y = 2.1
local TOUCH_SENSITIVTY_ADJUST_MIN_Y = 0.5
local VR_ANGLE = math.rad(15)
local VR_LOW_INTENSITY_ROTATION = Vector2.new(math.rad(15), 0)
local VR_HIGH_INTENSITY_ROTATION = Vector2.new(math.rad(45), 0)
local VR_LOW_INTENSITY_REPEAT = 0.1
local VR_HIGH_INTENSITY_REPEAT = 0.4
local ZERO_VECTOR2 = Vector2.new(0,0)
local ZERO_VECTOR3 = Vector3.new(0,0,0)
local TOUCH_SENSITIVTY = Vector2.new(0.00945 * math.pi, 0.003375 * math.pi)
local MOUSE_SENSITIVITY = Vector2.new( 0.002 * math.pi, 0.0015 * math.pi )
local SEAT_OFFSET = Vector3.new(0,5,0)
local VR_SEAT_OFFSET = Vector3.new(0,4,0)
local HEAD_OFFSET = Vector3.new(0,1.5,0)
local R15_HEAD_OFFSET = Vector3.new(0, 1.5, 0)
local R15_HEAD_OFFSET_NO_SCALING = Vector3.new(0, 2, 0)
local HUMANOID_ROOT_PART_SIZE = Vector3.new(2, 2, 1)
local GAMEPAD_ZOOM_STEP_1 = 0
local GAMEPAD_ZOOM_STEP_2 = 10
local GAMEPAD_ZOOM_STEP_3 = 20
local PAN_SENSITIVITY = 20
local ZOOM_SENSITIVITY_CURVATURE = 0.5
local abs = math.abs
local sign = math.sign
local FFlagUserCameraToggle do
local success, result = pcall(function()
return UserSettings():IsUserFeatureEnabled("UserCameraToggle")
end)
FFlagUserCameraToggle = success and result
end
local FFlagUserDontAdjustSensitvityForPortrait do
local success, result = pcall(function()
return UserSettings():IsUserFeatureEnabled("UserDontAdjustSensitvityForPortrait")
end)
FFlagUserDontAdjustSensitvityForPortrait = success and result
end
local FFlagUserFixZoomInZoomOutDiscrepancy do
local success, result = pcall(function()
return UserSettings():IsUserFeatureEnabled("UserFixZoomInZoomOutDiscrepancy")
end)
FFlagUserFixZoomInZoomOutDiscrepancy = success and result
end
local Util = _CameraUtils()
local ZoomController = _ZoomController()
local CameraToggleStateController = _CameraToggleStateController()
local CameraInput = _CameraInput()
local CameraUI = _CameraUI()
--[[ Roblox Services ]]--
local Players = game:GetService("Players")
local UserInputService = game:GetService("UserInputService")
local StarterGui = game:GetService("StarterGui")
local GuiService = game:GetService("GuiService")
local ContextActionService = game:GetService("ContextActionService")
local VRService = game:GetService("VRService")
local UserGameSettings = UserSettings():GetService("UserGameSettings")
local player = Players.LocalPlayer
--[[ The Module ]]--
local BaseCamera = {}
BaseCamera.__index = BaseCamera
function BaseCamera.new()
local self = setmetatable({}, BaseCamera)
-- So that derived classes have access to this
self.FIRST_PERSON_DISTANCE_THRESHOLD = FIRST_PERSON_DISTANCE_THRESHOLD
self.cameraType = nil
self.cameraMovementMode = nil
self.lastCameraTransform = nil
self.rotateInput = ZERO_VECTOR2
self.userPanningCamera = false
self.lastUserPanCamera = tick()
self.humanoidRootPart = nil
self.humanoidCache = {}
-- Subject and position on last update call
self.lastSubject = nil
self.lastSubjectPosition = Vector3.new(0,5,0)
-- These subject distance members refer to the nominal camera-to-subject follow distance that the camera
-- is trying to maintain, not the actual measured value.
-- The default is updated when screen orientation or the min/max distances change,
-- to be sure the default is always in range and appropriate for the orientation.
self.defaultSubjectDistance = math.clamp(DEFAULT_DISTANCE, player.CameraMinZoomDistance, player.CameraMaxZoomDistance)
self.currentSubjectDistance = math.clamp(DEFAULT_DISTANCE, player.CameraMinZoomDistance, player.CameraMaxZoomDistance)
self.inFirstPerson = false
self.inMouseLockedMode = false
self.portraitMode = false
self.isSmallTouchScreen = false
-- Used by modules which want to reset the camera angle on respawn.
self.resetCameraAngle = true
self.enabled = false
-- Input Event Connections
self.inputBeganConn = nil
self.inputChangedConn = nil
self.inputEndedConn = nil
self.startPos = nil
self.lastPos = nil
self.panBeginLook = nil
self.panEnabled = true
self.keyPanEnabled = true
self.distanceChangeEnabled = true
self.PlayerGui = nil
self.cameraChangedConn = nil
self.viewportSizeChangedConn = nil
self.boundContextActions = {}
-- VR Support
self.shouldUseVRRotation = false
self.VRRotationIntensityAvailable = false
self.lastVRRotationIntensityCheckTime = 0
self.lastVRRotationTime = 0
self.vrRotateKeyCooldown = {}
self.cameraTranslationConstraints = Vector3.new(1, 1, 1)
self.humanoidJumpOrigin = nil
self.trackingHumanoid = nil
self.cameraFrozen = false
self.subjectStateChangedConn = nil
-- Gamepad support
self.activeGamepad = nil
self.gamepadPanningCamera = false
self.lastThumbstickRotate = nil
self.numOfSeconds = 0.7
self.currentSpeed = 0
self.maxSpeed = 6
self.vrMaxSpeed = 4
self.lastThumbstickPos = Vector2.new(0,0)
self.ySensitivity = 0.65
self.lastVelocity = nil
self.gamepadConnectedConn = nil
self.gamepadDisconnectedConn = nil
self.currentZoomSpeed = 1.0
self.L3ButtonDown = false
self.dpadLeftDown = false
self.dpadRightDown = false
-- Touch input support
self.isDynamicThumbstickEnabled = false
self.fingerTouches = {}
self.dynamicTouchInput = nil
self.numUnsunkTouches = 0
self.inputStartPositions = {}
self.inputStartTimes = {}
self.startingDiff = nil
self.pinchBeginZoom = nil
self.userPanningTheCamera = false
self.touchActivateConn = nil
-- Mouse locked formerly known as shift lock mode
self.mouseLockOffset = ZERO_VECTOR3
-- [[ NOTICE ]] --
-- Initialization things used to always execute at game load time, but now these camera modules are instantiated
-- when needed, so the code here may run well after the start of the game
if player.Character then
self:OnCharacterAdded(player.Character)
end
player.CharacterAdded:Connect(function(char)
self:OnCharacterAdded(char)
end)
if self.cameraChangedConn then self.cameraChangedConn:Disconnect() end
self.cameraChangedConn = workspace:GetPropertyChangedSignal("CurrentCamera"):Connect(function()
self:OnCurrentCameraChanged()
end)
self:OnCurrentCameraChanged()
if self.playerCameraModeChangeConn then self.playerCameraModeChangeConn:Disconnect() end
self.playerCameraModeChangeConn = player:GetPropertyChangedSignal("CameraMode"):Connect(function()
self:OnPlayerCameraPropertyChange()
end)
if self.minDistanceChangeConn then self.minDistanceChangeConn:Disconnect() end
self.minDistanceChangeConn = player:GetPropertyChangedSignal("CameraMinZoomDistance"):Connect(function()
self:OnPlayerCameraPropertyChange()
end)
if self.maxDistanceChangeConn then self.maxDistanceChangeConn:Disconnect() end
self.maxDistanceChangeConn = player:GetPropertyChangedSignal("CameraMaxZoomDistance"):Connect(function()
self:OnPlayerCameraPropertyChange()
end)
if self.playerDevTouchMoveModeChangeConn then self.playerDevTouchMoveModeChangeConn:Disconnect() end
self.playerDevTouchMoveModeChangeConn = player:GetPropertyChangedSignal("DevTouchMovementMode"):Connect(function()
self:OnDevTouchMovementModeChanged()
end)
self:OnDevTouchMovementModeChanged() -- Init
if self.gameSettingsTouchMoveMoveChangeConn then self.gameSettingsTouchMoveMoveChangeConn:Disconnect() end
self.gameSettingsTouchMoveMoveChangeConn = UserGameSettings:GetPropertyChangedSignal("TouchMovementMode"):Connect(function()
self:OnGameSettingsTouchMovementModeChanged()
end)
self:OnGameSettingsTouchMovementModeChanged() -- Init
UserGameSettings:SetCameraYInvertVisible()
UserGameSettings:SetGamepadCameraSensitivityVisible()
self.hasGameLoaded = game:IsLoaded()
if not self.hasGameLoaded then
self.gameLoadedConn = game.Loaded:Connect(function()
self.hasGameLoaded = true
self.gameLoadedConn:Disconnect()
self.gameLoadedConn = nil
end)
end
self:OnPlayerCameraPropertyChange()
return self
end
function BaseCamera:GetModuleName()
return "BaseCamera"
end
function BaseCamera:OnCharacterAdded(char)
self.resetCameraAngle = self.resetCameraAngle or self:GetEnabled()
self.humanoidRootPart = nil
if UserInputService.TouchEnabled then
self.PlayerGui = player:WaitForChild("PlayerGui")
for _, child in ipairs(char:GetChildren()) do
if child:IsA("Tool") then
self.isAToolEquipped = true
end
end
char.ChildAdded:Connect(function(child)
if child:IsA("Tool") then
self.isAToolEquipped = true
end
end)
char.ChildRemoved:Connect(function(child)
if child:IsA("Tool") then
self.isAToolEquipped = false
end
end)
end
end
function BaseCamera:GetHumanoidRootPart()
if not self.humanoidRootPart then
if player.Character then
local humanoid = player.Character:FindFirstChildOfClass("Humanoid")
if humanoid then
self.humanoidRootPart = humanoid.RootPart
end
end
end
return self.humanoidRootPart
end
function BaseCamera:GetBodyPartToFollow(humanoid, isDead)
-- If the humanoid is dead, prefer the head part if one still exists as a sibling of the humanoid
if humanoid:GetState() == Enum.HumanoidStateType.Dead then
local character = humanoid.Parent
if character and character:IsA("Model") then
return character:FindFirstChild("Head") or humanoid.RootPart
end
end
return humanoid.RootPart
end
function BaseCamera:GetSubjectPosition()
local result = self.lastSubjectPosition
local camera = game.Workspace.CurrentCamera
local cameraSubject = camera and camera.CameraSubject
if cameraSubject then
if cameraSubject:IsA("Humanoid") then
local humanoid = cameraSubject
local humanoidIsDead = humanoid:GetState() == Enum.HumanoidStateType.Dead
if VRService.VREnabled and humanoidIsDead and humanoid == self.lastSubject then
result = self.lastSubjectPosition
else
local bodyPartToFollow = humanoid.RootPart
-- If the humanoid is dead, prefer their head part as a follow target, if it exists
if humanoidIsDead then
if humanoid.Parent and humanoid.Parent:IsA("Model") then
bodyPartToFollow = humanoid.Parent:FindFirstChild("Head") or bodyPartToFollow
end
end
if bodyPartToFollow and bodyPartToFollow:IsA("BasePart") then
local heightOffset
if humanoid.RigType == Enum.HumanoidRigType.R15 then
if humanoid.AutomaticScalingEnabled then
heightOffset = R15_HEAD_OFFSET
if bodyPartToFollow == humanoid.RootPart then
local rootPartSizeOffset = (humanoid.RootPart.Size.Y/2) - (HUMANOID_ROOT_PART_SIZE.Y/2)
heightOffset = heightOffset + Vector3.new(0, rootPartSizeOffset, 0)
end
else
heightOffset = R15_HEAD_OFFSET_NO_SCALING
end
else
heightOffset = HEAD_OFFSET
end
if humanoidIsDead then
heightOffset = ZERO_VECTOR3
end
result = bodyPartToFollow.CFrame.p + bodyPartToFollow.CFrame:vectorToWorldSpace(heightOffset + humanoid.CameraOffset)
end
end
elseif cameraSubject:IsA("VehicleSeat") then
local offset = SEAT_OFFSET
if VRService.VREnabled then
offset = VR_SEAT_OFFSET
end
result = cameraSubject.CFrame.p + cameraSubject.CFrame:vectorToWorldSpace(offset)
elseif cameraSubject:IsA("SkateboardPlatform") then
result = cameraSubject.CFrame.p + SEAT_OFFSET
elseif cameraSubject:IsA("BasePart") then
result = cameraSubject.CFrame.p
elseif cameraSubject:IsA("Model") then
if cameraSubject.PrimaryPart then
result = cameraSubject:GetPrimaryPartCFrame().p
else
result = cameraSubject:GetModelCFrame().p
end
end
else
-- cameraSubject is nil
-- Note: Previous RootCamera did not have this else case and let self.lastSubject and self.lastSubjectPosition
-- both get set to nil in the case of cameraSubject being nil. This function now exits here to preserve the
-- last set valid values for these, as nil values are not handled cases
return
end
self.lastSubject = cameraSubject
self.lastSubjectPosition = result
return result
end
function BaseCamera:UpdateDefaultSubjectDistance()
if self.portraitMode then
self.defaultSubjectDistance = math.clamp(PORTRAIT_DEFAULT_DISTANCE, player.CameraMinZoomDistance, player.CameraMaxZoomDistance)
else
self.defaultSubjectDistance = math.clamp(DEFAULT_DISTANCE, player.CameraMinZoomDistance, player.CameraMaxZoomDistance)
end
end
function BaseCamera:OnViewportSizeChanged()
local camera = game.Workspace.CurrentCamera
local size = camera.ViewportSize
self.portraitMode = size.X < size.Y
self.isSmallTouchScreen = UserInputService.TouchEnabled and (size.Y < 500 or size.X < 700)
self:UpdateDefaultSubjectDistance()
end
-- Listener for changes to workspace.CurrentCamera
function BaseCamera:OnCurrentCameraChanged()
if UserInputService.TouchEnabled then
if self.viewportSizeChangedConn then
self.viewportSizeChangedConn:Disconnect()
self.viewportSizeChangedConn = nil
end
local newCamera = game.Workspace.CurrentCamera
if newCamera then
self:OnViewportSizeChanged()
self.viewportSizeChangedConn = newCamera:GetPropertyChangedSignal("ViewportSize"):Connect(function()
self:OnViewportSizeChanged()
end)
end
end
-- VR support additions
if self.cameraSubjectChangedConn then
self.cameraSubjectChangedConn:Disconnect()
self.cameraSubjectChangedConn = nil
end
local camera = game.Workspace.CurrentCamera
if camera then
self.cameraSubjectChangedConn = camera:GetPropertyChangedSignal("CameraSubject"):Connect(function()
self:OnNewCameraSubject()
end)
self:OnNewCameraSubject()
end
end
function BaseCamera:OnDynamicThumbstickEnabled()
if UserInputService.TouchEnabled then
self.isDynamicThumbstickEnabled = true
end
end
function BaseCamera:OnDynamicThumbstickDisabled()
self.isDynamicThumbstickEnabled = false
end
function BaseCamera:OnGameSettingsTouchMovementModeChanged()
if player.DevTouchMovementMode == Enum.DevTouchMovementMode.UserChoice then
if (UserGameSettings.TouchMovementMode == Enum.TouchMovementMode.DynamicThumbstick
or UserGameSettings.TouchMovementMode == Enum.TouchMovementMode.Default) then
self:OnDynamicThumbstickEnabled()
else
self:OnDynamicThumbstickDisabled()
end
end
end
function BaseCamera:OnDevTouchMovementModeChanged()
if player.DevTouchMovementMode.Name == "DynamicThumbstick" then
self:OnDynamicThumbstickEnabled()
else
self:OnGameSettingsTouchMovementModeChanged()
end
end
function BaseCamera:OnPlayerCameraPropertyChange()
-- This call forces re-evaluation of player.CameraMode and clamping to min/max distance which may have changed
self:SetCameraToSubjectDistance(self.currentSubjectDistance)
end
function BaseCamera:GetCameraHeight()
if VRService.VREnabled and not self.inFirstPerson then
return math.sin(VR_ANGLE) * self.currentSubjectDistance
end
return 0
end
function BaseCamera:InputTranslationToCameraAngleChange(translationVector, sensitivity)
if not FFlagUserDontAdjustSensitvityForPortrait then
local camera = game.Workspace.CurrentCamera
if camera and camera.ViewportSize.X > 0 and camera.ViewportSize.Y > 0 and (camera.ViewportSize.Y > camera.ViewportSize.X) then
-- Screen has portrait orientation, swap X and Y sensitivity
return translationVector * Vector2.new( sensitivity.Y, sensitivity.X)
end
end
return translationVector * sensitivity
end
function BaseCamera:Enable(enable)
if self.enabled ~= enable then
self.enabled = enable
if self.enabled then
self:ConnectInputEvents()
self:BindContextActions()
if player.CameraMode == Enum.CameraMode.LockFirstPerson then
self.currentSubjectDistance = 0.5
if not self.inFirstPerson then
self:EnterFirstPerson()
end
end
else
self:DisconnectInputEvents()
self:UnbindContextActions()
-- Clean up additional event listeners and reset a bunch of properties
self:Cleanup()
end
end
end
function BaseCamera:GetEnabled()
return self.enabled
end
function BaseCamera:OnInputBegan(input, processed)
if input.UserInputType == Enum.UserInputType.Touch then
self:OnTouchBegan(input, processed)
elseif input.UserInputType == Enum.UserInputType.MouseButton2 then
self:OnMouse2Down(input, processed)
elseif input.UserInputType == Enum.UserInputType.MouseButton3 then
self:OnMouse3Down(input, processed)
end
end
function BaseCamera:OnInputChanged(input, processed)
if input.UserInputType == Enum.UserInputType.Touch then
self:OnTouchChanged(input, processed)
elseif input.UserInputType == Enum.UserInputType.MouseMovement then
self:OnMouseMoved(input, processed)
end
end
function BaseCamera:OnInputEnded(input, processed)
if input.UserInputType == Enum.UserInputType.Touch then
self:OnTouchEnded(input, processed)
elseif input.UserInputType == Enum.UserInputType.MouseButton2 then
self:OnMouse2Up(input, processed)
elseif input.UserInputType == Enum.UserInputType.MouseButton3 then
self:OnMouse3Up(input, processed)
end
end
function BaseCamera:OnPointerAction(wheel, pan, pinch, processed)
if processed then
return
end
if pan.Magnitude > 0 then
local inversionVector = Vector2.new(1, UserGameSettings:GetCameraYInvertValue())
local rotateDelta = self:InputTranslationToCameraAngleChange(PAN_SENSITIVITY*pan, MOUSE_SENSITIVITY)*inversionVector
self.rotateInput = self.rotateInput + rotateDelta
end
local zoom = self.currentSubjectDistance
local zoomDelta = -(wheel + pinch)
if abs(zoomDelta) > 0 then
local newZoom
if self.inFirstPerson and zoomDelta > 0 then
newZoom = FIRST_PERSON_DISTANCE_THRESHOLD
else
if FFlagUserFixZoomInZoomOutDiscrepancy then
if (zoomDelta > 0) then
newZoom = zoom + zoomDelta*(1 + zoom*ZOOM_SENSITIVITY_CURVATURE)
else
newZoom = (zoom + zoomDelta) / (1 - zoomDelta*ZOOM_SENSITIVITY_CURVATURE)
end
else
newZoom = zoom + zoomDelta*(1 + zoom*ZOOM_SENSITIVITY_CURVATURE)
end
end
self:SetCameraToSubjectDistance(newZoom)
end
end
function BaseCamera:ConnectInputEvents()
self.pointerActionConn = UserInputService.PointerAction:Connect(function(wheel, pan, pinch, processed)