Turns out, making a character swing realistically is a lot harder than the tutorial makes it seem. The tutorial assumes that I am coding a character controller from scratch. Although that would be the easiest way to implement swinging, it's also the hardest way to make a character controller - I'd have to implement my own collision system, my own movement mechanics, etc. All perfectly doable, but Unity comes with lots of handy built-in features to save me from doing that kind of work. I actually tried implementing my own avatar movement script first, which worked fine until I tried to do collisions at which point it started to not play so nice. I got them working, sort of, but the amount of polish that I would have to put into getting that script to look and feel good didn't seem worth it when Unity could just do that work for me.
So I switched to Unity's built-in character controller. Worked great! Automatic collision detection and simplified movement mechanics. Really, all I have to do with that is give the script a vector (a point in 3D space with distance and direction) and the character controller will move along that vector while remaining constrained by collisions. So far, so good.
But what about the swinging? The tutorial was no longer relevant, since it didn't address the vector movement of a swinging character. I would have to calculate the vector of movement along the arc of the swing, which meant (I thought) finding the proper tangent vector to the sphere representing the length of the rope around the tether point. There are an infinite number of tangent vectors to any given point along a sphere. I scoured the internet, I talked to professors, I tried wild guesses that had amusing but useless results. Finally a brilliant friend of mine (a physics major) took a look at what I was doing.
"You know, the only force a rope exerts when you swing on it is towards the origin of the rope."
IT WAS SO SIMPLE. All I had to do was add the vector pointing from the character to the rope to the character's movement vector. Voila - swinging like Spider Man. I still have to make some tweaks to make it feel good, but those are details.
If I ever become successful enough to have employees, my first hire will be a physicist.
Here is a brilliant interactive novella about a kiss.
Great story -- great solution! Looking forward to future installments.
ReplyDelete