Get closest direction to a vector

I have a weather app on an in game phone in my game and I want it to display what direction the GlobalWind is blowing (north, south, east, west).

These are my directions:

		local directions = {
			{Direction = Vector3.new(1,0,0), Name = "East"},
			{Direction = Vector3.new(-1,0,0), Name = "West"},
			{Direction = Vector3.new(0,0,1), Name = "South"},
			{Direction = Vector3.new(0,0,-1), Name = "North"},
			{Direction = Vector3.new(1,0,-1), Name = "Northeast"},
			{Direction = Vector3.new(-1,0,-1), Name = "Northwest"},
			{Direction = Vector3.new(1,0,1), Name = "Southeast"},
			{Direction = Vector3.new(-1,0,1), Name = "Southwest"},
		}

How can I find the direction closest to what GlobalWind currently is?

It might not be the most efficient, but you can dot GlobalWind with each of the direction vectors and choose the vector that resulted in the highest value.

If you take the dot product of two unit vectors, 1 means they are in the same direction, -1 means they are in the opposite direction, and 0 means they are perpendicular. Using this, given any vector the closest direction will be the one with the highest dot product (when normalizing the vectors).

local function GetDirection(vector)
	vector = vector.Unit
	
	local matchingDirection
	local maxProduct = -math.huge
	
	for i, direction in pairs(directions) do
		local product = vector:Dot(direction.Direction.Unit)
		if product > maxProduct then
			maxProduct = product
			matchingDirection = direction
		end
	end
	
	return matchingDirection
end

local vector = Vector3.new(1, 0, 0.1)
local direction = GetDirection(vector)
print(direction.Name) -- "East"
1 Like

Thank you!

chars

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.