Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

What would be a good way to tell if a player hits another player from behind?

Asked by
Romul 21
5 years ago

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!

0
ray casting, region3, ect User#24403 69 — 5y

1 answer

Log in to vote
1
Answered by
fredfishy 833 Moderation Voter
5 years ago

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)
    -- 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

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.

Ad

Answer this question