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

Angle between two vectors3s?

Asked by
BenSBk 781 Moderation Voter
6 years ago

How would I find the angle between two vector3s?

2 answers

Log in to vote
2
Answered by
EgoMoose 802 Moderation Voter
6 years ago

RubenKan explained how to get the direction between two vectors, but if you're actually looking for the angle between them you want the dot product.

local function angleBetween(a, b)
    return math.acos(a:Dot(b) / (a.magnitude * b.magnitude));
end;

Keep in mind this angle will be between 0 and 180 degrees.

2
More succinctly, `math.acos(a.Unit:Dot(b.Unit))` BlueTaslem 18071 — 6y
0
Thanks. Is there any way I can use this to return an angle between 0 and 360 degrees? BenSBk 781 — 6y
0
Yes, you need to use the 'math.deg()' function to get the answer back in degrees (and not radians). See my original post's function, which does this. The answer will always be between 0 and 180, because the range of arc cosine is [0, pi]. See here: http://www.analyzemath.com/Graphing/graphing_arccosine.html WillieTehWierdo200 966 — 6y
0
Thanks - no way to detect if the part is behind the other part, then? BenSBk 781 — 6y
View all comments (2 more)
0
I don't see how that relates to this question? WillieTehWierdo200 966 — 6y
0
Sorry for the late response, I had to go let my cat out. I was just wondering if there was a workaround for the 0–180 degrees lock. I wanted a full 360 degrees range to check if a part was behind another part, though now realise there's better ways of doing this. Thanks again. BenSBk 781 — 5y
Ad
Log in to vote
0
Answered by 6 years ago

According to this example, I created a function for you that calculates the angle (in degrees) between two Vector3 variables.

-- Returns angle between two vectors (in degrees)
function angleBetween(v1, v2)
  return math.deg(math.acos(v1:Dot(v2)/(v1.Magnitude*v2.Magnitude)))
end

-- Use like this
local angle = angleBetween(Vector3.new(2,9,-3), Vector3.new(-3,-4,8))
print(angle)
0
Thanks for the help! I believe EgoMoose’s post has a comment that utilises Roblox’s own functions. BenSBk 781 — 6y
0
EgoMoose's code is no different from mine, although BlueTaslem did propose a shortcut by using the unit vectors from the get-go. WillieTehWierdo200 966 — 6y

Answer this question