• entries
743
1924
• views
584348

# Swinging on a Spring

889 views

I've got the basics of a spring mass working as a rope now. It needs a fair bit of tweaking but it works okay, as evidenced by this poor quality video:

The maths is actually quite easy to implement for this. In among the other code for the kinematic character controller, we just add this formula, just before we do the collision test with the world:[code=:0] if(ropeActive) { Vec3 rv = (pos + vel) - ropePos; float r = vectorLength(rv); float k = 0.05f; float len = 6; vel += -(rv / r) * (r - len) * k; }
k is the spring constant and can be set higher to make the spring stiffer, and len is the rest length of the spring. The last line is simpler than it looks. rv / r is just the normalized vector between the position and the rope anchor (I already have the length so cheaper to do this than call normalizeVector()) and r - len is the difference (positive or negative) between the rope rest length and the actual length.

The result is just added to the velocity, which is then added to the position of the character later in the method as normal.

Surprisingly, it works pretty well. The character switches between swinging and being a more normal controller on the ground as I want. Need to tweak some of the character's velocity when falling through the air a bit, and various other bits and pieces to make it feel as I want, but the basic idea is working well.

Doing a rope that bends around corners like in my 2.5D version of this will be slightly trickier as the rope is going to need to slide along edges as the player moves through the extra dimension, but all should be possible to puzzle out I'm sure. The other big question is whether my idea about being able to click anywhere and have the rope attach to everything is going to be a feasible mechanic, but no way to know how that will work out without trying it.

I like the convex shape collision detection

Thank you. Was a lot of work and frustration to get working and robust

## Create an account

Register a new account