Procedure
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).
Flattening
Cut out the vertical components of the vectors:
function flatten(vec3)
return Vector3.new(vec3.x, 0, vec3.z)
end
Getting the angle
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|) )
Magnitude
We could get magnitude as follows:
function magnitude(vec3)
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
Calculating dot product
Calculate the dot product the vectors
function dot(a, b)
return a.x * b.x + a.y * b.y + a.z * b.z
end
Combining
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.
1 comment
ray casting, region3, ect