Skip to content

Instantly share code, notes, and snippets.

@Nimblz
Last active October 4, 2019 00:50
Show Gist options
  • Save Nimblz/5d6147b0b98a48250a10c2bb0aa65110 to your computer and use it in GitHub Desktop.
Save Nimblz/5d6147b0b98a48250a10c2bb0aa65110 to your computer and use it in GitHub Desktop.
Uses dark magic (math) to calculate the unit velocity vector that will create a trajectory to your goal given a speed
function calcTrajectoryTheta(start,goal,speed,pickHighAngle)
local xzStart = start * Vector3.new(1,0,1)
local xzGoal = goal * Vector3.new(1,0,1)
local range = (xzGoal-xzStart).Magnitude
local yDiff = goal.Y - start.Y
local g = workspace.Gravity
if range == 0 then return nil end
if g == 0 then
return math.atan(yDiff/range) -- simply return angle to the goal
end
local insideSqrt = (speed*speed*speed*speed) - (g * (g*range*range + 2*yDiff*speed*speed))
if insideSqrt < 0 then return nil end -- NaN will happen
local sqrt = math.sqrt(insideSqrt)
local angleOne = (speed*speed + sqrt)/(g*range)
local angleTwo = (speed*speed - sqrt)/(g*range)
angleOne = math.atan(angleOne)
angleTwo = math.atan(angleTwo)
if pickHighAngle then
return math.max(angleOne,angleTwo)
else
return math.min(angleOne,angleTwo)
end
end
function directionToReachGoal(start,goal,speed,pickHighAngle)
local theta = calcTrajectoryTheta(start,goal,speed,pickHighAngle)
if not theta then return nil end
local facingDirection = ((goal-start) * Vector3.new(1,0,1)).Unit
local facingCFrame = CFrame.new(Vector3.new(), facingDirection)
local angledCFrame = facingCFrame * CFrame.fromAxisAngle(Vector3.new(1,0,0), theta)
return angledCFrame.LookVector
end
return directionToReachGoal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment