Advertisement
Alenvei

Curve smoother function for Path2D

Jan 15th, 2024 (edited)
978
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
GDScript 1.56 KB | Gaming | 0 0
  1. @tool
  2. extends Path2D
  3.  
  4. # Exported variable to control the smoothness of the curve
  5. @export var smoothness : float = 100
  6.  
  7. # Variables to store points and tangents
  8. var last_point
  9. var next_point
  10. var start_tangent
  11. var end_tangent
  12.  
  13. # Called every frame. 'delta' is the elapsed time since the previous frame.
  14. func _process(delta):
  15.     # Function to smooth the curve
  16.     curve_smooth()
  17.  
  18. func curve_smooth():
  19.     # Iterate through each point in the curve
  20.     for i in curve.get_point_count():
  21.         var pos =  curve.get_point_position(i)
  22.         print(i)
  23.        
  24.         # Set the last point to the current point if it's the first point in the curve
  25.         if i == 0:
  26.             last_point = curve.get_point_position(0)
  27.         else:
  28.             last_point = curve.get_point_position(i - 1)
  29.            
  30.         # Set the next point to the next point in the curve or Vector2.ZERO if it's the last point
  31.         if i != curve.get_point_count() - 1:
  32.             next_point = curve.get_point_position(i + 1)
  33.         else:
  34.             next_point = Vector2.ZERO
  35.            
  36.         # Calculate directions and tangents
  37.         var last_dir = (pos - last_point)
  38.         var next_dir = (next_point - pos)
  39.        
  40.         start_tangent = (last_dir + next_dir) * smoothness
  41.         end_tangent = (next_dir + last_dir) * (-1) * smoothness
  42.        
  43.         # Set tangents for points that are not the first or last
  44.         if i != 0 and i != curve.get_point_count() - 1:
  45.             curve.set_point_in(i, end_tangent)
  46.             curve.set_point_out(i, start_tangent)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement