I am attempting to create a radar system, it already displays positions of detected objects on a display but I need to be able to rotate those positions around the center by the rotation of the display.
I have researched this problem but any details I could find online didn't function properly and caused more problems.
...
for i, ship in ipairs(scan) do
local xOffset = currentPos['x'] - ship['position']['x']
local zOffset = currentPos['z'] - ship['position']['z']
--Rotate xOffset and zOffset around center (0,0)
local drawX = xMiddle + xOffset
local drawZ = zMiddle + zOffset
paintutils.drawPixel(drawX, drawZ, colors.blue)
local textLen = string.len(ship['mass'])
local textStart = drawX - textLen/2
term.setCursorPos(textStart, drawZ-1)
term.write(ship['mass'])
end
...
One simple way to rotate 2d cartesian coordinates x
, y
around the origin by an angle delta
is to convert them to polar coordinates, then apply the rotation, then convert them back to cartesian coordinates. In code this looks as follows:
-- Rotates (x, y) around origin by the angle delta (in radians, counterclockwise)
local function rotate(x, y, delta)
-- Convert to polar coordinates
local length, angle = math.sqrt(x^2 + y^2), math.atan2(y, x)
-- Rotate by delta
angle = angle + delta
-- Convert back to cartesian coordinates
return length * math.cos(angle), length * math.sin(angle)
end
Example usage:
> rotate(1, 0, math.pi/4)
0.70710678118655 0.70710678118655
This rotates the point (1, 0) by 45° (pi/4
in radians) counterclockwise, correctly yielding (sqrt(2), sqrt(2)).
If you use Lua 5.3 or newer, you'll have to use math.atan
(which accepts two arguments) instead of math.atan2
.
If you prefer degrees, simply use math.rad(deg)
to convert your degrees to radians.