ANIMAL WELL vine physics

GameANIMAL WELL
Built withUnity 6 (6000.4.3f1)

What I’m looking at

The puzzle metroidvania ANIMAL WELL has a lot of vines hanging from the ceiling. They have physics like real rope, so they move when the player walks through them.

The yo-yo passing through a curtain of vines and pushing them aside. Source: Shared Memory / Bigmode, ANIMAL WELL Release Date Trailer (Steam), 0:18–0:21

I wanted to know how vines like these are built, so I decided to make them myself.

I couldn’t find the developer’s own explanation of how the vine physics works. There is a standard technique for this kind of thing, though, so that’s what I’ll go through.

One vine

The simplest approach is to draw a swaying animation ahead of time and play it when the player touches the vine. But an animation plays the same way every time, which is far from what I’m after here. For short grass you can get away with rotation or a shader, but what I want is a long rope. On the other hand, if you put a Rigidbody and a joint on every segment, the more joints you add, the more the segments stretch or jitter, and it’s too heavy for dozens of vines.

The approach games have used for ropes and cloth for a long time is Verlet integration plus distance constraints. Thomas Jakobsen reportedly built it for the cloth, plants and ragdolls in Hitman: Codename 47 and presented it at GDC 2001. It’s simple, fast, and hard to blow up.

Verlet integration

A single vine is one fixed point stuck in the ceiling plus N points hanging below it at even spacing. Imagine an invisible rod of length LL between each pair of neighboring points. Each point doesn’t store a velocity. It only remembers its current position and its position on the last frame.

The formula looks like this.

xnew=x+(x−xprev)⋅k+g Δt2x_{\text{new}} = x + (x - x_{\text{prev}})\cdot k + g\,\Delta t^2

xx is the current position and xprevx_{\text{prev}} is the position on the last frame. x−xprevx - x_{\text{prev}} is the velocity, how far the point moved over the last frame. kk is a damping factor of around 0.95–0.99. Keeping it a little under 1 makes the swinging die down slowly. The last term, g Δt2g\,\Delta t^2, is the movement that gravity adds. Once the calculation is done, this frame’s xx goes into xprevx_{\text{prev}} to get ready for the next frame.

I implemented this formula in FixedUpdate. kk is damping, and g Δt2g\,\Delta t^2 is Physics2D.gravity (0, −9.81) multiplied by fixedDeltaTime squared.

// VineChain.cs, FixedUpdate()
var g = Physics2D.gravity * (Time.fixedDeltaTime * Time.fixedDeltaTime);
// Verlet integration: velocity is the difference from the last position
for (int i = 1; i <= segments; ++i)
{
    var v = (pos[i] - prev[i]) * damping;
    prev[i] = pos[i];
    pos[i] += v + g;
}

Keeping rod length with distance constraints

With integration alone, gravity pulls the points down and the chain keeps stretching. So right after integrating, a correction pulls the distance between each pair of neighboring points back to the rod length LL.

Δ=d−Ld (p2−p1),p1+=12Δ,p2−=12Δ\Delta = \frac{d - L}{d}\,(p_2 - p_1), \qquad p_1 \mathrel{+}= \tfrac{1}{2}\Delta,\quad p_2 \mathrel{-}= \tfrac{1}{2}\Delta

dd is the current distance between the two points. (d−L)/d(d-L)/d is how much the rod stretched, as a ratio, and multiplying it by the vector between the two points gives the displacement Δ\Delta that has to be taken back out.

But with many points, correcting one point knocks the next one out of place again. So the pass that corrects every point in order runs several times per frame (usually 4–10). Too few passes and the vine sags like a rubber band. More passes make it stiffer and more accurate.

In the code, LL is segLength and the number of passes is iterations. In the scene I set iterations to 8.

// VineChain.cs, FixedUpdate()
// Repeat rod correction and push-out
for (int k = 0; k < iterations; k++)
{
    pos[0] = transform.position;
    for (int i = 1; i <= segments; ++i)
    {
        var d = pos[i] - pos[i - 1];
        float len = Mathf.Max(d.magnitude, 1e-5f);
        var delta = d * ((len - segLength) / len);
        if (i == 1) pos[i] -= delta;
        else
        {
            pos[i - 1] += delta * 0.5f;
            pos[i] -= delta * 0.5f;
        }
    }
    PushOut();
}

For the record, the vines are drawn with a LineRenderer and a URP 2D Unlit material.

Vine collision

All you have to do is move any point that ends up inside the player’s (or another object’s) collider out past the nearest edge. That gives you collision handling without any complicated collision math.

One thing to watch: the push-out has to run inside the distance constraint loop from before. That’s why PushOut() sits inside the loop in the code above. If you push out only once, outside the loop, the distance correction drags points back inside the collider.

PushOut only checks the bounds that fall inside the vine’s AABB. If a point is inside one of those bounds, it gets pushed left or right. At first I actually had it find the nearest side out of all four directions, but the values kept jumping whenever the player jumped, so I switched to pushing only left or right.

// VineChain.cs, PushOut()
for (int i = 1; i <= segments; ++i)
{
    var p = pos[i];
    for (int j = 0; j != bounds.Count; ++j)
    {
        var b = bounds[j];
        // Careful: points exactly on the boundary have to be excluded too
        if (p.x <= b.min.x || p.x >= b.max.x || p.y <= b.min.y || p.y >= b.max.y)
            continue;

        bool fromLeft = prev[i].x < b.center.x;
        p.x = fromLeft ? b.min.x : b.max.x;
        contact[i] = true;
    }

    pos[i] = p;
}

Once the loop finishes, the velocity from being pushed is scaled by pushTransfer (0.2 in the scene). The bigger the value, the more of that velocity is kept. I added it because when the player moved fast or jumped around, the vines got pushed away too easily, and I needed a way to control how much push velocity they keep.

// VineChain.cs, FixedUpdate()
for (int i = 1; i <= segments; ++i)
{
    if (!contact[i]) continue;
    prev[i] = pos[i] - (pos[i] - prev[i]) * pushTransfer;
}
Pushing out in all four directions, no pushTransfer
Pushing out only left and right, pushTransfer 0.2

Many vines

When a scene has a lot of vines, is it fine to simulate all of them?

First, a rough cost estimate. Say there are 60 vines on screen, 20 points per vine, and 6 correction passes. That’s 60×20×6=7,20060 \times 20 \times 6 = 7{,}200 rod corrections per frame. One correction is a few subtractions and multiplications plus one square root, so on a modern CPU that’s a tiny fraction of 1 ms. In other words, simulating every vine on screen is entirely doable.

And since ANIMAL WELL’s camera moves one screen at a time, limiting the work to the vines in the room you can see puts a natural cap on the cost.

Only simulate what’s touched (sleep)

Still, only a few vines might be touching the player, so simulating every idle vine every frame is wasteful. My first thought was: couldn’t vines use something like the sleep that physics engines use, and simulate only the ones that get touched?

  • If every point on a vine has moved only a tiny distance for a set number of frames (e.g. 30 frames, 0.5 s), put it to sleep.
  • Give objects a wake range a bit bigger than their collider, and wake a vine when that range overlaps the vine’s bounding box.
  • When a vine goes to sleep, its velocity has to be set to 0.

You could put the wake range on the player, but adding it to every moving object would be inefficient, so I reused the vine’s collision AABB. Every frame I compute the box (AABB) around all of the vine’s points myself, grow it by queryMargin (0.1), and use Physics2D.OverlapArea to find the colliders that overlap that box. The terrain’s CompositeCollider has to be left out of pushMask.

// VineChain.cs, Touching()
// Compute the AABB around the whole vine ourselves.
Vector2 min = pos[0], max = pos[0];
for (int i = 1; i <= segments; ++i)
{
    min = Vector2.Min(min, pos[i]);
    max = Vector2.Max(max, pos[i]);
}
min -= Vector2.one * queryMargin;
max += Vector2.one * queryMargin;

// Find colliders that overlap the vine's rectangle.
Physics2D.OverlapArea(min, max, filter, hits);

bounds.Clear();
foreach(var c in hits)
    bounds.Add(c.bounds);

return bounds.Count > 0;
// VineChain.cs, FixedUpdate()
float moved = 0f;
for (int i = 1; i <= segments; ++i)
    moved = Mathf.Max(moved, (pos[i] - prev[i]).sqrMagnitude);
if (moved < 1e-7f && !touching)
{
    if (++stillFrames > 30) // sleep
    {
        awake = false;
        Array.Copy(pos, prev, pos.Length);
    }
}
else stillFrames = 0;

Vine shadows

By shadow I mean light from a light source being blocked directly.

Honestly, I’m not sure whether the original game computes vine shadows. I was curious, so I tried it anyway.

Vertex rays don’t fit

For an ordinary polygon, you cast rays from the light to the polygon’s vertices to build the area the light reaches (a visibility polygon). But vines move a lot and are built from plain points, so this doesn’t fit.

How the demo does it

In my demo I built it with Shadow Caster 2D and EdgeCollider2D. Each vine gets an EdgeCollider2D, and at the end of every FixedUpdate the point positions go straight into the edge’s points. Shadow Caster 2D is set to use this edge’s shape as the shadow shape, and the scene has a Spot Light 2D.

// VineChain.cs, UpdateShadowEdge()
edgePoints.Clear();
for(int i = 0; i <= segments; ++i)
    edgePoints.Add(transform.InverseTransformPoint(pos[i]));
shadowEdge.SetPoints(edgePoints);

The collider’s Exclude layer has to be set to Everything, and the vine layer has to be left out of pushMask.

Walking through the vines in a lit room, 2x speed

This isn’t the one right way to do it. Another option is an occlusion mask.

Last thoughts

Verlet integration can be used for many structures made of connected points that need inertia, such as cloth, water surfaces, tentacles, and worm-like monsters.

References

Asset credits

  • Luneblade — Art by Jesshiyoo

About

Seongwon Choi 최성원

Game Programmer

qwik0102@gmail.com