Advertisement
Guest User

SplinePath

a guest
Aug 18th, 2020
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.71 KB | None | 0 0
  1. --[[
  2.     SplinePath v1.0 by Waffle
  3.  
  4.     This module takes an ordered table of positions and defines a curve that passes through the given list of nodes.
  5.     SplinePath.PointOnPath(nodeList, progress) takes a progress argument between 0 and 1 and returns a position along the curve.
  6.     SplinePath.FollowPath(object, nodeList, duration) moves an object along the path in the given amount of time.
  7. ]]
  8.  
  9. local SplinePath = {}
  10.  
  11. function SplinePath.PointOnPath(nodeList, progress) -- catmull-rom cubic hermite interpolation
  12.     if progress == 1 then return nodeList[#nodeList] end
  13.     local index1 = math.floor(1 + progress * (#nodeList - 1))
  14.     local index2 = index1 + 1
  15.    
  16.     local point1 = nodeList[index1]
  17.     local point2 = nodeList[index2]
  18.     local tangent1 = (point2 - nodeList[math.max(1, index1 - 1)]) / 2
  19.     local tangent2 = (nodeList[math.min(#nodeList, index1 + 2)] - point1) / 2
  20.    
  21.     local alpha = (progress * (#nodeList - 1)) % 1
  22.    
  23.     local h1 =  2*alpha^3 - 3*alpha^2 + 1
  24.     local h2 = -2*alpha^3 + 3*alpha^2
  25.     local h3 =    alpha^3 - 2*alpha^2 + alpha
  26.     local h4 =    alpha^3 -   alpha^2
  27.    
  28.     return h1*point1 + h2*point2 + h3*tangent1 + h4*tangent2
  29. end
  30.  
  31.  
  32. function SplinePath.FollowPath(object, nodeList, duration)
  33.     local progress = 0
  34.     local updatePeriod = .1
  35.     while true do
  36.         updatePeriod = Task.Wait()
  37.         if not Object.IsValid(object) then return end
  38.         progress = progress + updatePeriod / duration
  39.         if progress > 1 then break end
  40.         local point = SplinePath.PointOnPath(nodeList, progress)
  41.         object:MoveContinuous((point - object:GetWorldPosition()) / updatePeriod)
  42.         object:RotateTo(Rotation.New(point - object:GetWorldPosition(), Vector3.UP), updatePeriod)
  43.     end
  44.     object:MoveTo(nodeList[#nodeList], updatePeriod)
  45. end
  46.  
  47. return SplinePath
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement