So I’m currently making a game about racing, and I made a simple script that fires everytime a player moves and It does 3 things:
- Increase/Decrease the player speed until It reaches the max/min speed.
- Change the player’s character physical properties so It slips.
- Enable a “smoke” particle effect when the humanoid speed is low (When the humanoid accelerates or slows down).
I feel that I can improve the code a lot in many different ways, but I already scripted 2 times the code from scratch and still didn’t made so much improvement.
local RunService = game:GetService("RunService")
local ServerStorage = game:GetService("ServerStorage")
local TweenService = game:GetService("TweenService") --This service is used for other part of the code, ignore it.
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local MovementValues = ServerStorage:WaitForChild("MovementValues", 100)
local PlayerEvents = ReplicatedStorage:WaitForChild("PlayerEvents", 100)
local DefaultSpeed = MovementValues.DEFAULT_SPEED.Value --(60)
local SmokeSpeed = MovementValues.SMOKE_SPEED.Value --(45)
local MaxSpeed = MovementValues.MAX_SPEED.Value --(70)
local function RunningSmoke(Character, State)
local RightLeg = Character:WaitForChild("Right Leg", 5)
local LeftLeg = Character:WaitForChild("Left Leg", 5)
RightLeg.RunSmoke.RunSmoke.Enabled = State
LeftLeg.RunSmoke.RunSmoke.Enabled = State
end
local function RootPartPhysics(Hrp, Density)
Hrp.CustomPhysicalProperties = PhysicalProperties.new(Density, 0, 0, 50, 0)
end
game.ReplicatedStorage.PlayerEvents.PlayerMove.OnServerEvent:Connect(function(Player, Character, Humanoid, Hrp, IsMoving)
if (not Character or not Humanoid or not Hrp or Humanoid:GetState() == Enum.HumanoidStateType.Dead) then
return
end
local BodySpeed = Hrp.Velocity.Magnitude
if (IsMoving >= 1 and Humanoid.WalkSpeed <= MaxSpeed) then
Humanoid.WalkSpeed = Humanoid.WalkSpeed + .1
elseif (IsMoving <= 0 and Humanoid.WalkSpeed >= DefaultSpeed or BodySpeed < Humanoid.WalkSpeed and Humanoid.WalkSpeed >= DefaultSpeed) then
RootPartPhysics(Hrp, .4)
Humanoid.WalkSpeed = Humanoid.WalkSpeed - .5
end
if (IsMoving >= 1 and BodySpeed <= SmokeSpeed) then
RunningSmoke(Character, true)
RootPartPhysics(Hrp, .4)
elseif (IsMoving <= 0 or BodySpeed >= SmokeSpeed or Humanoid.WalkSpeed >= (MaxSpeed - 5)) then
RunningSmoke(Character, false)
RootPartPhysics(Hrp, .8)
end
end)
If my explanation was so bad, you can check the place where I’m doing this so you can test what the code does.