Mryeetmemes

Some roblox script I found in the new roblox studio template named 'Chassis'

May 15th, 2023
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 13.40 KB | None | 0 0
  1. local Workspace = game:GetService("Workspace")
  2. local RunService = game:GetService("RunService")
  3.  
  4. local PackagedScripts = script.Parent
  5. local PackagedVehicle = PackagedScripts.Parent
  6.  
  7. local Effects = require(PackagedScripts:WaitForChild("Effects"))
  8.  
  9. local constraints = PackagedVehicle:WaitForChild("Constraints")
  10.  
  11. local mphConversion = 0.6263 -- using a 28cm = 1stud conversion rate
  12.  
  13. --[[ Chassis Variables ]]--
  14. local VehicleParameters = { -- These are default values in the case the package structure is broken
  15.     MaxSpeed = 75/mphConversion,
  16.     ReverseSpeed = 45/mphConversion,
  17.     DrivingTorque = 30000,
  18.     BrakingTorque = 70000,
  19.     StrutSpringStiffnessFront = 28000,
  20.     StrutSpringDampingFront = 1430,
  21.     StrutSpringStiffnessRear = 27000,
  22.     StrutSpringDampingRear = 1400,
  23.     TorsionSpringStiffness = 20000,
  24.     TorsionSpringDamping = 150,
  25.     MaxSteer = 0.55,
  26.     WheelFriction = 2
  27. }
  28.  
  29. local Chassis = nil
  30. local LimitSteerAtHighVel = true
  31. -- Limits the amount you can steer based on velocity. Helpful for keyboard/non-analog steer inputs
  32. local SteerLimit = 0.2 -- Max amount the steering float (-1 to 1) will be limited by if limitSteerAtHighVel is true
  33.  
  34. local DoGravityAdjust = true -- Adjust chassis values based on the current gravity setting.
  35. local ActualDrivingTorque
  36. local ActualBrakingTorque
  37. local ActualStrutSpringStiffnessFront
  38. local ActualStrutSpringDampingFront
  39. local ActualStrutSpringStiffnessRear
  40. local ActualStrutSpringDampingRear
  41. local ActualTorsionSpringStiffness
  42. local ActualTorsionSpringDamping
  43.  
  44. -- Adjust torque and springs based on gravity to keep the car drivable
  45. local function gravityAdjust()
  46.     local defaultGravity = 196.2
  47.     local actualGravity = Workspace.Gravity
  48.     local gravityChange = actualGravity / defaultGravity
  49.     -- Speed is adjusted so that the height of jumps is preserved
  50.     -- So maxSpeed is scaled proportionally to the sqrt of gravity
  51.     ActualDrivingTorque = VehicleParameters.DrivingTorque * gravityChange
  52.     ActualBrakingTorque = VehicleParameters.BrakingTorque * gravityChange
  53.  
  54.     ActualStrutSpringStiffnessFront = VehicleParameters.StrutSpringStiffnessFront * gravityChange
  55.     ActualStrutSpringDampingFront = VehicleParameters.StrutSpringDampingFront * math.sqrt( gravityChange )
  56.     ActualStrutSpringStiffnessRear = VehicleParameters.StrutSpringStiffnessRear * gravityChange
  57.     ActualStrutSpringDampingRear = VehicleParameters.StrutSpringDampingRear * math.sqrt( gravityChange )
  58.  
  59.     ActualTorsionSpringStiffness = VehicleParameters.TorsionSpringStiffness * gravityChange
  60.     ActualTorsionSpringDamping = VehicleParameters.TorsionSpringDamping * math.sqrt( gravityChange )
  61. end
  62.  
  63. local function convertProperty(property, value)
  64.     if property == "MaxSpeed" or property == "ReverseSpeed" then
  65.         -- convert to studs/sec
  66.         return value / mphConversion
  67.     end
  68.  
  69.     return value
  70. end
  71.  
  72. local changedAttributesConnection = nil
  73. local function updateFromConfiguration()
  74.     local obj = script.Parent.Parent
  75.  
  76.     for property, value in pairs(VehicleParameters) do
  77.         local configProp = obj:GetAttribute(property)
  78.  
  79.         if configProp then
  80.             VehicleParameters[property] = convertProperty(property, configProp)
  81.         end
  82.     end
  83.  
  84.     -- Handle dynamic changes
  85.     changedAttributesConnection = obj.AttributeChanged:Connect(function(property)
  86.         -- Only handle attributes we're interested in
  87.         if VehicleParameters[property] == nil then
  88.             return
  89.         end
  90.  
  91.         local value = obj:GetAttribute(property)
  92.         VehicleParameters[property] = convertProperty(property, value)
  93.  
  94.         if DoGravityAdjust then
  95.             gravityAdjust()
  96.         end
  97.  
  98.         if Chassis then
  99.             Chassis.InitializeDrivingValues() -- reinitialize chassis so that changes are reflected in the rig
  100.         end
  101.     end)
  102. end
  103.  
  104. updateFromConfiguration()
  105.  
  106. if DoGravityAdjust then
  107.     gravityAdjust()
  108. end
  109.  
  110. workspace.Changed:Connect(function(prop)
  111.     if prop == "Gravity" then
  112.         if DoGravityAdjust then
  113.             gravityAdjust()
  114.         end
  115.         if Chassis then
  116.             Chassis.InitializeDrivingValues() -- reinitialize chassis so that changes are reflected in the rig
  117.         end
  118.     end
  119. end)
  120.  
  121. local Motors
  122. local SteeringPrismatic
  123. local RedressMount
  124.  
  125. --[[ Private Functions ]]--
  126. local function getVehicleMotors()
  127.     local motors = {}
  128.     for _, c in pairs(constraints:GetChildren()) do
  129.         if c:IsA("CylindricalConstraint") then
  130.             table.insert(motors, c)
  131.         end
  132.     end
  133.     return motors
  134. end
  135.  
  136. local function getSprings(springType)
  137.     local springs = {}
  138.     local trailer = PackagedVehicle:FindFirstChild("Trailer")
  139.    
  140.     local function search(children)
  141.         local searchStrutSpring = "StrutSpring"
  142.         local searchFrontSpring = "StrutSpringF"
  143.         local searchTorsionSpring = "TorsionBarSpring"
  144.         for _, c in pairs(children) do
  145.             if c:IsA("SpringConstraint") then
  146.                 if springType == "StrutFront" then
  147.                     if string.find(c.Name, searchFrontSpring) then
  148.                         table.insert(springs, c)
  149.                     end
  150.                 elseif springType == "StrutRear" then
  151.                     if (not string.find(c.Name, searchFrontSpring)) and string.find(c.Name, searchStrutSpring) then
  152.                         table.insert(springs, c) -- we have option of Mid and Rear for these
  153.                     end
  154.                 elseif springType == "TorsionBar" then
  155.                     if string.find(c.Name, searchTorsionSpring) then
  156.                         table.insert(springs, c)
  157.                     end
  158.                 end
  159.             end
  160.         end
  161.     end
  162.  
  163.     search(constraints:GetChildren())
  164.     if trailer then
  165.         search(trailer.Constraints:GetChildren())
  166.     end
  167.    
  168.     return springs
  169. end
  170.  
  171. local function getMotorVelocity(motor)
  172.     return motor.Attachment1.WorldAxis:Dot( motor.Attachment1.Parent.RotVelocity )
  173. end
  174.  
  175. local function adjustSpring( spring, stiffness, damping )
  176.     spring.Stiffness = stiffness
  177.     spring.Damping = damping
  178. end
  179.  
  180. local function setMotorTorque(torque)
  181.     for _, motor in pairs(Motors) do       
  182.         motor.MotorMaxTorque = torque
  183.     end
  184. end
  185.  
  186. local function setMotorTorqueDamped(torque, velocityDirection, accelDirection)
  187.     for _, motor in pairs(Motors) do
  188.         if VehicleParameters.MaxSpeed == 0 then
  189.             motor.MotorMaxTorque = 0
  190.         else
  191.             local maxSpeed = VehicleParameters.MaxSpeed
  192.             if accelDirection < 0 and velocityDirection < 0 then
  193.                 maxSpeed = VehicleParameters.ReverseSpeed
  194.             end
  195.            
  196.             local r = math.abs(Chassis.driverSeat.Velocity.Magnitude / maxSpeed)
  197.             motor.MotorMaxTorque = math.exp( -3 * r * r ) * torque
  198.         end
  199.     end
  200. end
  201.  
  202. local function setMotorMaxAcceleration(acceleration)
  203.     for _, motor in pairs(Motors) do
  204.         motor.MotorMaxAngularAcceleration = acceleration
  205.     end
  206. end
  207.  
  208. --[[ Module Functions ]]--
  209. Chassis = {}
  210.  
  211. Chassis.root = PackagedVehicle:FindFirstChild("Chassis") --the root of the Chassis model
  212. Chassis.driverSeat = Chassis.root:FindFirstChildOfClass("VehicleSeat")
  213. Chassis.passengerSeats = {
  214.         Chassis.root:FindFirstChild("SeatFR"),
  215.         Chassis.root:FindFirstChild("SeatRL"),
  216.         Chassis.root:FindFirstChild("SeatRR")
  217. }
  218.  
  219. local randomSuspension = Chassis.root:FindFirstChild("SuspensionFL")
  220. local wheelRadius = randomSuspension.Wheel.Size.y/2
  221. Chassis.driverSeat.MaxSpeed = VehicleParameters.MaxSpeed * wheelRadius
  222.  
  223. function Chassis.InitializeDrivingValues()
  224.     -- Constraint tables always ordered FL, FR, RL, RR
  225.     Motors = getVehicleMotors()
  226.    
  227.     local strutSpringsFront = getSprings("StrutFront")
  228.     local strutSpringsRear = getSprings("StrutRear")
  229.     local torsionSprings = getSprings("TorsionBar")
  230.  
  231.     RedressMount = Chassis.root:WaitForChild("RedressMount")
  232.    
  233.     SteeringPrismatic = constraints:FindFirstChild("SteeringPrismatic")
  234.     SteeringPrismatic.UpperLimit = VehicleParameters.MaxSteer
  235.     SteeringPrismatic.LowerLimit = -VehicleParameters.MaxSteer
  236.  
  237.     for _,s in pairs(strutSpringsFront) do
  238.         adjustSpring(s, ActualStrutSpringStiffnessFront, ActualStrutSpringDampingFront)
  239.     end
  240.     for _,s in pairs(strutSpringsRear) do
  241.         adjustSpring(s, ActualStrutSpringStiffnessRear, ActualStrutSpringDampingRear)
  242.     end
  243.     for _,s in pairs(torsionSprings) do
  244.         adjustSpring(s, ActualTorsionSpringStiffness, ActualTorsionSpringDamping)
  245.     end
  246.    
  247.     local chassisChildren = Chassis.root:GetChildren()
  248.     for i = 1, #chassisChildren do
  249.         local model = chassisChildren[i]
  250.         if model:IsA("Model") then
  251.             local wheel = model:FindFirstChild("Wheel")
  252.             if wheel then
  253.                 local old = wheel.CustomPhysicalProperties
  254.                 local new = PhysicalProperties.new(old.Density, VehicleParameters.WheelFriction, old.Elasticity, old.FrictionWeight, old.ElasticityWeight)
  255.                 wheel.CustomPhysicalProperties = new
  256.             end
  257.         end
  258.     end
  259.  
  260.     setMotorTorque(10000)
  261. end
  262.  
  263. function Chassis.GetDriverSeat()
  264.     return Chassis.driverSeat
  265. end
  266.  
  267. function Chassis.GetPassengerSeats()
  268.     return Chassis.passengerSeats
  269. end
  270.  
  271. function Chassis.GetBase()
  272.     return Chassis.root.PrimaryPart or Chassis.root:FindFirstChild("FloorPanel")
  273. end
  274.  
  275. --Set target angular velocity for all 4 wheels.
  276. function Chassis.SetMotorVelocity(vel)
  277.     for _, motor in pairs(Motors) do
  278.         motor.AngularVelocity = vel
  279.     end
  280. end
  281.  
  282. --Get average angular velocity from all 4 wheels
  283. function Chassis.GetAverageVelocity()
  284.     local t = 0
  285.     for _, motor in pairs(Motors) do
  286.         t = t + getMotorVelocity(motor)
  287.     end
  288.     return t * (1/#Motors)
  289. end
  290.  
  291. --Set braking torque and stop back 2 wheels
  292. function Chassis.EnableHandbrake()
  293.     setMotorMaxAcceleration(math.huge)
  294.     Motors[3].MotorMaxTorque = ActualBrakingTorque
  295.     Motors[4].MotorMaxTorque = ActualBrakingTorque
  296.     Motors[3].AngularVelocity = 0
  297.     Motors[4].AngularVelocity = 0
  298. end
  299.  
  300. --Set target steering position based on current velocity
  301. function Chassis.UpdateSteering(steer, currentVel)
  302.     local baseSteer = steer
  303.     local targetSteer = 0
  304.    
  305.     local vehicleSeat = Chassis.GetDriverSeat()
  306.     local maxSpeed = VehicleParameters.MaxSpeed
  307.     local maxSteer = VehicleParameters.MaxSteer
  308.    
  309.     local currentVelocity = vehicleSeat.Velocity
  310.    
  311.     if LimitSteerAtHighVel then
  312.         local c = SteerLimit * (math.abs(currentVel)/VehicleParameters.MaxSpeed) + 1
  313.         --decrease steer value as speed increases to prevent tipping (handbrake cancels this)
  314.         steer = steer/c
  315.     end
  316.     SteeringPrismatic.TargetPosition = steer * steer * steer * maxSteer
  317. end
  318.  
  319. function Chassis.UpdateThrottle(currentSpeed, throttle)
  320.     local targetVel = 0
  321.     local effectsThrottleState = false
  322.     local gainModifier = 0
  323.    
  324.     if math.abs(throttle) < 0.1 then
  325.         -- Idling
  326.         setMotorMaxAcceleration(math.huge)
  327.         setMotorTorque(2000)
  328.     elseif math.sign(throttle * currentSpeed) > 0 or math.abs(currentSpeed) < 0.5 then
  329.         setMotorMaxAcceleration(math.huge)
  330.        
  331.         local velocity = Chassis.driverSeat.Velocity
  332.         local velocityVector = velocity.Unit
  333.         local directionalVector = Chassis.driverSeat.CFrame.lookVector
  334.         local dotProd = velocityVector:Dot(directionalVector) -- Dot product is a measure of how similar two vectors are; if they're facing the same direction, it is 1, if they are facing opposite directions, it is -1, if perpendicular, it is 0
  335.        
  336.         setMotorTorqueDamped(ActualDrivingTorque * throttle * throttle, dotProd, math.sign(throttle))
  337.         -- Arbitrary large number
  338.         local movingBackwards = dotProd < 0
  339.         local acceleratingBackwards = throttle < 0
  340.         local useReverse = (movingBackwards and acceleratingBackwards)
  341.        
  342.         local maxSpeed = (useReverse and VehicleParameters.ReverseSpeed or VehicleParameters.MaxSpeed)
  343.         targetVel = math.sign(throttle) * maxSpeed
  344.        
  345.         -- if we are approaching max speed, we should take that as an indication of throttling down, even if not from input
  346.         local maxAccelSpeed = targetVel
  347.         local speedPercent = ((maxAccelSpeed-currentSpeed)/maxAccelSpeed) -- 0 if max speed, 1 if stopped
  348.        
  349.         -- lets say we start throttling down after reaching 75% of max speed, then linearly drop to 0
  350.         local function quad(x)
  351.             return math.sign(x)*(x^2)
  352.         end
  353.        
  354.        
  355.         local r = math.abs(velocity.Magnitude / maxSpeed*2.5) -- adding a bit to the max speed so that it sounds better (always trying to rev engines)
  356.         local desiredRPM = math.exp(-3*r*r)
  357.        
  358.        
  359.         gainModifier = desiredRPM
  360.        
  361.         if gainModifier > 0 then
  362.             effectsThrottleState = true
  363.         end
  364.     else
  365.         -- Braking
  366.         setMotorMaxAcceleration(100)
  367.         setMotorTorque(ActualBrakingTorque * throttle * throttle)
  368.         targetVel = math.sign(throttle) * 500
  369.     end
  370.    
  371.     Chassis.SetMotorVelocity(targetVel)
  372.    
  373.     Effects:SetThrottleEnabled(effectsThrottleState, gainModifier)
  374.  
  375. end
  376.  
  377. local redressingState = false
  378. local targetAttachment
  379. function Chassis.Redress()
  380.     if redressingState then
  381.         return
  382.     end
  383.     redressingState = true
  384.     local p = Chassis.driverSeat.CFrame.Position + Vector3.new( 0,10,0 )
  385.     local xc = Chassis.driverSeat.CFrame.RightVector
  386.     xc = Vector3.new(xc.x,0,xc.z)
  387.     xc = xc.Unit
  388.     local yc = Vector3.new(0,1,0)
  389.  
  390.     if not targetAttachment then
  391.         targetAttachment = RedressMount.RedressTarget
  392.     end
  393.  
  394.     targetAttachment.Parent = Workspace.Terrain
  395.     targetAttachment.Position = p
  396.     targetAttachment.Axis = xc
  397.     targetAttachment.SecondaryAxis = yc
  398.     RedressMount.RedressOrientation.Enabled = true
  399.     RedressMount.RedressPosition.Enabled = true
  400.     wait(1.5)
  401.     RedressMount.RedressOrientation.Enabled = false
  402.     RedressMount.RedressPosition.Enabled = false
  403.     targetAttachment.Parent = RedressMount
  404.     wait(2)
  405.     redressingState = false
  406. end
  407.  
  408. function Chassis.Reset() --Reset user inputs and redress (For when a player exits the vehicle)
  409.     Chassis.UpdateThrottle(1, 1) --Values must  be changed to replicate to client.
  410.     Chassis.UpdateSteering(1, 0) --i.e. setting vel to 0 when it is 0 wont update to clients
  411.     Chassis.EnableHandbrake()
  412.     setMotorTorque(ActualBrakingTorque)
  413.     Chassis.SetMotorVelocity(0)
  414.     Chassis.UpdateSteering(0, 0)
  415.     RedressMount.RedressOrientation.Enabled = true
  416.     RedressMount.RedressPosition.Enabled = true
  417.     RedressMount.RedressOrientation.Enabled = false
  418.     RedressMount.RedressPosition.Enabled = false
  419.     redressingState = false
  420. end
  421.  
  422. return Chassis
  423.  
Add Comment
Please, Sign In to add comment