I don't have a code example for this, but I have a method to state that I'm currently using and the problems with it. I'd like to detect when a player his hit from behind to tie in with my guarding functions.
Currently, I have an invisible brick behind the player that is detected whenever it is hit and that runs the behind hit functions. The problem with this is when a player hits from in front, sometimes it hits the thin, invisible brick behind the player first and this runs the behind function even though they hit from in front.
I'd appreciate any help on this, thanks!
Basically, we're going to use the dot product to derive a formula for getting the angle between two vectors
First, we need to find the forward vector of the torso, and the incoming vector of the brick (relatively trivial and implementation based, so left as an exercise to the reader).
Cut out the vertical components of the vectors:
function flatten(vec3) return Vector3.new(vec3.x, 0, vec3.z) end
The dot product between two vectors is defined as |u| |v| cos x = u . v
, where |u|
means the magnitude (length) of the vector. We can rearrange that to get x as follows:
|u| |v| cos x = u . v cos x = (u . v) / (|u| |v|) x = arccos ( (u . v) / (|u| |v|) )
We could get magnitude as follows:
function magnitude(vec3) -- By Pythagoras' Theorem local x2 = math.pow(vec3.x, 2) local y2 = math.pow(vec3.y, 2) local z2 = math.pow(vec3.z, 2) return math.sqrt(x2, y2, z2) end
But Lua has an in-built method for this in Vector3::magnitude
Calculate the dot product the vectors
function dot(a, b) return a.x * b.x + a.y * b.y + a.z * b.z end
Then we can put it all together
function getAngle(a, b) return math.acos(dot(a, b) / (a.magnitude() * b.magnitude())) end
Note that this answer will be in radians rather than degrees.