Notifications
Article
Direction based hit reactions in Unity
Published a year ago
83
0
The problem
So my enemies were lacking some reactions to getting hit by weapons among other things that would make things more juicy, I decided to use the morning to implement a simple hit reaction system.
The solution
My first stop was to add a hit animation in a way that would layer over the rest of the enemy systems, so I created a simple 10 frame animation with one pose to see how it looked, I added this to a separate layer on-top of every other layer - named it HitLayer. Created an upper body mask so that they could still walk and then I just triggered it upon getting hit using Animator.SetTrigger:
https://www.youtube.com/watch?v=m5iPEokriiY
​https://gfycat.com/gifs/detail/ShyCooperativeGalapagospenguin
That worked fine, so then I had to figure out a way of establishing the direction the weapon or projectile was coming through, luckily Unity has a dot product function as well as a working sample in the SDK (https://docs.unity3d.com/ScriptReference/Vector3.Dot.html) that recognized forward and behind. I extended this to recognize left and right. I also gave it some tolerance to allow for centered directions, so 8 directions in total and a centered one just to cover all possibilities.
I first tested this using a cube and a sphere:
https://www.youtube.com/watch?v=-bYamUCiRV8
​https://gfycat.com/gifs/detail/ThinOffbeatBear
So now that this was working I went back into 3dsmax and made the 8 directional hit poses, roughly, then brought them back in to Unity and named the accordingly. I then added them all to the hit layer I created and placed them according to direction,

string Direction (Vector3 OtherObject) { string front; string right; float tolerance = 0.15f; if (Vector3.Dot(transform.forward, OtherObject - transform.position) < -tolerance) front = "Back"; else if (Vector3.Dot(transform.forward, OtherObject - transform.position) > tolerance) front = "Front"; else front = "Center"; if (Vector3.Dot(transform.right, OtherObject - transform.position) < -tolerance) right = "Left"; else if (Vector3.Dot(transform.right, OtherObject - transform.position) > tolerance) right = "Right"; else right = "Center"; return front + right; }

finished up the transition setup, I called these using the same method as I used above and voila:
https://www.youtube.com/watch?v=huAPPEkeKVg
https://gfycat.com/gifs/detail/MeaslyWhirlwindAfricanmolesnake
Optimization note: I found this https://forum.unity.com/threads/animator-dont-use-setbool-string-name-with-string-parameter.406286/ about setting triggers with strings and will update my code when I am polishing things up, but for now I just wanted to make sure everything is working as expected
Swearsoft
GameDev with an attitude - Other
4
Comments