Issue causes diverging velocity

  1. What do you want to achieve?
    I want the magnitude of acceleration to follow the script that I have. I have an equation that takes in miles per hour, and changes the power of the engine accordingly. This then changes the magnitude to which knobPositionRatio can accelerate the train, slowing the rate which velocity can be increased. I know this will also slow down deceleration, but I am currently not worried about that since I plan to have a simple fix for that. Here is the function that it is modeled on, where x is inputted mph, and y is the output power. I don’t need it to work for values above 75 mph, only from 0-75.

Here is the code:

local part = script.Parent.Parent.Engine
local vectorForce = Instance.new("BodyVelocity", part)
vectorForce.MaxForce = Vector3.new(50000000000,50000000000,50000000000)
vectorForce.P = 50000000000
local velocity = 0
local Power = 2
local Drag = 0.05
local acceleration = 0.5
while true do
	wait(0.01)
	local studsPerSecond = (part.AssemblyLinearVelocity * Vector3.new(1,0,1)).Magnitude
	local mph = studsPerSecond/1.448
	local Power = 2.13-(0.0025*(mph^1.5))
	local re = game.ReplicatedStorage.re
	re.OnServerEvent:connect(function(player,knobPositionRatio)
		acceleration = knobPositionRatio
	end)
	velocity = velocity - (acceleration - 0.5)
	if velocity < 0 then
		velocity = 0
		vectorForce.velocity = Vector3.new(0,0,0)
	end
	if velocity >= 0 then 
		local a = velocity*Power
		vectorForce.velocity = part.CFrame.lookVector * a
	end
end
  1. What is the issue? Include screenshots / videos if possible!
    This code which should work fine in theory, actually starts to cause a divergence of velocity around 55 mph when tested.

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    It just doesn’t work the way it’s supposed to. The next thing I am considering to do is instead change the knobPositionRatio value and shift it as a function of mph, which would also solve the slowing deceleration problem I have. Thus, I would leave Power as a constant instead of changing it.

Ran it at a slower increment, the divergence starts around 49.1, if that helps.

I’ve read the code, but it would take slightly more time to make sure I fully understand it all, mostly since I’m not that familiar with the imperial system.

However, you are currently using a BodyVelocity (roblox.com), which has been deprecated. You should use LinearVelocity (roblox.com) instead. Also, consider changing your wait() to task.wait(), it is a more accurate and overall just a better version of wait().

Have you tried printing out a, Power and mph? mph is received from a division from an “ugly” number., same with power. Consider working in studs and only convert it to mph for display to the user, alternatively convert studs to meters.

1 Like