Skip to content

Instantly share code, notes, and snippets.

@Zarkonnen
Created May 13, 2026 06:18
Show Gist options
  • Select an option

  • Save Zarkonnen/e85d8baaa853998241a68488b2db9746 to your computer and use it in GitHub Desktop.

Select an option

Save Zarkonnen/e85d8baaa853998241a68488b2db9746 to your computer and use it in GitHub Desktop.
Catenary calculation functions in c#
// Function to calculate y-value of catenary curve at a particular x-value.
public static float CatenaryY(Vector2 start, Vector2 end, float length, float x) {
float h = end.X - start.X;
float v = end.Y - start.Y;
float a = FindA(h, v, length);
float p = (start.X + end.X - a * MathF.Log((length + v) / (length - v))) / 2;
float q = (start.Y + end.Y - length * (1 / MathF.Tanh(h / (2 * a)))) / 2;
return a * MathF.Cosh((x - p) / a) + q;
}
// Helper function to find the correct value for a.
public static float FindA(float h, float v, float l) {
// You can't calculate a, you can only pick a number and then check how well it works.
// Do a linear scan of possible values for a first.
// Note that the code I derived this from uses a *much* smaller step, but this step size yields
// the fastest results for where I'm using it. YMMV.
const float step = 50f;
float a = 0;
do
{
a += step;
}
while (MathF.Sqrt(MathF.Pow(l, 2) - MathF.Pow(v, 2)) < 2 * a * MathF.Sinh(h / (2 * a)));
// Again, the code I derived this from uses a much higher target precision, but this is enough
// for my needs.
const float precision = 0.1f;
float aPrev = a - step;
float aNext = a;
do
{
a = (aPrev + aNext) / 2f;
if (Math.Sqrt(Math.Pow(l, 2) - Math.Pow(v, 2)) < 2 * a * MathF.Sinh(h / (2 * a))) {
aPrev = a;
} else {
aNext = a;
}
} while (aNext - aPrev > precision);
return a;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment