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

Trying to get an angle through the dot product, what's wrong with my script?

Asked by 6 years ago
local Guard = script.Parent
local GuardRoot = Guard:WaitForChild("HumanoidRootPart")
local GuardHumanoid = Guard:WaitForChild("Humanoid")
local Player = game.Workspace:WaitForChild("SneakySecretAgent")
local PlayerRoot = Player:WaitForChild("HumanoidRootPart")

while true do
    wait()  
    local PlayerPosition = PlayerRoot.Position

    local GuardFace = GuardRoot.CFrame.lookVector
    local PlayerFromGuard = PlayerPosition - GuardPosition

    local Product = GuardFace:Dot(PlayerFromGuard)
    local Cos = math.cos(Product)
    local Angle = math.acos(Cos)

end

Basically the dot product part works well (hopefully), as I'm trying to see if the a guard can see the player, which in turn means I need to use the dot product to check how much the guard is facing the player.

Problem is, I want to reduce the sight of the guard, but I need to get the angle using the dot product. My script doesn't seem to input the correct angle.

Thanks in advance

1 answer

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

I looked up the formula for the angle between two vectors here (since you are trying to get the angle between the guard's line of vision and where the player is in relation to the guard): http://www.wikihow.com/Find-the-Angle-Between-Two-Vectors

Here is the implementation of that formula (I tested it and it works) in Roblox-lua:

function AngleBetweenVectors(a, b)
    return math.acos(a:Dot(b) / (a.Magnitude * b.Magnitude))
end

Note that it's giving it to you in radians, so if you want degrees you'll want to apply math.deg to it. ex:

print(math.deg(AngleBetweenVectors(Vector3.new(1, 0, 0), Vector3.new(5, 0, 5)))) -- prints a number very close to 45
0
Hey man! Thanks for your own interpretation of that guide. I seem to have screwed it right there. hehe SneakySecretAgent 12 — 6y
Ad

Answer this question