I’m trying to fire out a projectile that moves towards my mouse, following a bezier curve. However, the distance between myself and the end position changes how fast the projectile moves, how would I make it maintain a certain speed?
local bodyPos = Instance.new("BodyPosition",newBall)
bodyPos.MaxForce = Vector3.new(math.huge,math.huge,math.huge)
bodyPos.P = 50000
bodyPos.Position = newBall.Position
local endPos = mouseRemote:InvokeClient(plr)
local startPos = newBall.Position
local curveOffset = (CFrame.new((endPos+startPos)/2) * CFrame.new(xOffset * 1.5,yOffset * 1.5,zOffset * 1.5)).Position
local function lerp(p1,p2,t)
return p1 + (p2-p1) * t
end
local speed = 100
for i = 0,speed do
local t = i/speed
local l1 = lerp(startPos,curveOffset,t)
local l2 = lerp(curveOffset,endPos,t)
local curve = lerp(l1,l2,t)
bodyPos.Position = curve
wait(0.01)
end
You can get the total length of the curve, then do local time = distance/speed where speed is a constant value. And use the time variable to set how quickly it has to move.
In this case, you would put the time variable in your wait() at the end. So like wait(time) instead of wait(0.01) . Also the smallest wait value you can use is 0.03, and wait() is depreciated. Use task.wait() as the alternative
In addition to the problem you are facing now, you may also need to use some arc-length parameterization for your Bézier curve to make sure the speed does not change throughout the curve. See more about that here under the “Arc-Length Parameterization” section: Bézier Curves | Roblox Creator Documentation
Putting time into my wait variable causes the projectile to stutter, waiting a few seconds before it moves.
local speed = 50
local distance = (startPos-endPos).Magnitude
local Time = distance/speed
print(Time)
for i = 0,speed do
local t = i/speed
local l1 = lerp(startPos,curveOffset,t)
local l2 = lerp(curveOffset,endPos,t)
local curve = lerp(l1,l2,t)
bodyPos.Position = curve
task.wait(Time)
end```