So I made this code:
yVeloc = script.Parent.MaxForce.Y repeat yVeloc = (yVeloc - 1) until yVeloc == 0
So yVeloc is a BodyVelocity's MaxForce's Y.
I am trying to make it decrease by 1 (from 4000 to 0), to simulate an effect of real gravity.
But the problem is, it won't change the variable.
Can I have some help, please?
The issue is that you're changing the variable's value, not the object's property's value. You'd also want to add some sort of yielding statement so that you don't cause performance issues with a loop like that
local bodyVelocity = script.Parent local function changeGravity(delta) bodyVelocity.MaxForce = Vector3.new( bodyVelocity.MaxForce.X, bodyVelocity.MaxForce.Y + delta, bodyVelocity.MaxForce.Z ) end
Creating a function will be easier since you cannot set the Y value of the MaxForce property alone.
Now we'll need to create a function to simulate the gravity and reduce the maximum force.
local function simulateGravity(duration) repeat changeGravity(-1) wait(duration / 4000) until bodyVelocity.MaxForce.Y == 0 end
The issue with this code is that it's not best for performance either. This is why we'll try connecting to an event, see how much time has elapsed since the start to determine how much to reduce the gravity by, and then reduce it.
We'll connect to the Stepped event (since this works on both server and client).
We'll then need to know how much time has elapsed since the start, so we know where we are. We'll call this variable deltaTime
.
Once we know how much time passed, we should find out what percentage of the way we are. This percentage will be between 0 and 1. This number is how much we should subtract from the gravity since it's meant to decrease over time. We'll find out how much by subtracting it from 1 so we get the percentage we need to subtract.
Once we have this, we can multiply it by 4000 to properly scale it.
local function simulateGravity(duration) local startTime = tick() local connection local lastGravity = 4000 connection = game:GetService("RunService").Stepped:Connect(function() local deltaTime = tick() - startTime local newGravity = 4000 * (1 - deltaTime / duration) setGravity(newGravity - lastGravity) if newGravity == 0 then connection:Disconnect() end end) end