I'm trying to do some simple thing but I do fail over and over I did try about 20 different things.
The idea is very simple I want to get the compass direction from the current position heading to the destination.
At the moment I use vectors using https://github.com/themousery/vector.lua.
So I have A and B and have the vector heading, with that heading I want to know the exact compass direction.
What I was using before, but that one is not 100% correct.
Code: Select all
local function getOctant(heading)
return Math.round(16 * heading / (2 * math.pi)) % 16
-- return Math.round(16 * heading / (2 * math.pi) + 16) % 16
end
local c = getOctant(vDirection:heading())
-- ^ the result was not 1:1 with the table below
Compass.E = 0
Compass.ENE = 1
Compass.NE = 2
Compass.NNE = 3
Compass.N = 4
Compass.NNW = 5
Compass.NW = 6
Compass.WNW = 7
Compass.W = 8
Compass.WSW = 9
Compass.SW = 10
Compass.SSW = 11
Compass.S = 12
Compass.SSE = 13
Compass.SE = 14
Compass.ESE = 15
https://stackoverflow.com/questions/624 ... -javascrip
https://www.physicsclassroom.com/mmedia/vectors/vd.cfm
https://gamedev.stackexchange.com/quest ... -compass-d
https://stackoverflow.com/questions/368 ... conversion
https://p5js.org/reference/#/p5.Vector/heading
Code: Select all
-- old thing
-- local angleInRadians =
-- math.atan2(self.vPosition.y, self.vPosition.x) - math.atan2(self.vDestination.y, self.vDestination.x)
Code: Select all
local fromToTest = {
-- current x, current y, dest x, dest y, compass
{Vector(0, 0), Vector(0, 0), nil},
{Vector(0, 0), Vector(0, 1), "N"} -- fail it say S
}
for _, fromTo in pairs(fromToTest) do
local vPosition = fromTo[1]
local vDestination = fromTo[2]
local headingCompassDirection = fromTo[3]
local x = vPosition.x - vDestination.x
local y = vPosition.y - vDestination.y
local t = (((math.acos(y / math.sqrt(x * x + y * y)) * (Math.sign(y) or 1)) * 180 / math.pi) + 360) % 360
local arr = {
"N",
"NNE",
"NE",
"ENE",
"E",
"ESE",
"SE",
"SSE",
"S",
"SSW",
"SW",
"WSW",
"W",
"WNW",
"NW",
"NNW",
"N"
}
local res = arr[Math.round(((t % 360) / 22.5) + 1)]
lu.assertEquals(res, headingCompassDirection)
end