Search code examples
luaellipselove2d

How to "rotate" an ellipse?


Using this:

local W, H = 100, 50

function love.draw()
  love.graphics.translate(love.graphics.getWidth()/2,love.graphics.getHeight()/2)
  for i = 1, 360 do
    local I = math.rad(i)
    local x,y = math.cos(I)*W, math.sin(I)*H
    love.graphics.line(0, 0, x, y)
  end
end

I can connect a line with the center of an ellipse (with length W and height H) and the edge. How do you 'rotate' the ellipse around it's center, with a parameter R? I know you can sort of do it with love.graphics.ellipse and love.graphics.rotate but is there any way I can get the coordinates of the points on a rotated ellipse?


Solution

  • This is a Trigonometry problem, here is how the basic 2D rotation work. Imagine a point located at (x,y). If you want to rotate that point around the origin(in your case 0,0) by the angle θ, the coordinates of the new point would be located at (x1,y1) by using the following transformation

    x1 = xcosθ − ysinθ
    y1 = ycosθ + xsinθ

    In your example, I added a new ellipse after rotations

    function love.draw()
        love.graphics.translate(love.graphics.getWidth()/2,love.graphics.getHeight()/2)
        for i = 1, 360, 5 do
            local I = math.rad(i)
            local x,y = math.cos(I)*W, math.sin(I)*H
            love.graphics.setColor(0xff, 0, 0) -- red
            love.graphics.line(0, 0, x, y)
        end
    
      -- rotate by angle r = 90 degree
        local r = math.rad(90)
        for i = 1, 360, 5 do
            local I  = math.rad(i)
            -- original coordinates
            local x  = math.cos(I) * W 
            local y  = math.sin(I) * H
            -- transform coordinates
            local x1 = x * math.cos(r) - y * math.sin(r) 
            local y1 = y * math.cos(r) + x * math.sin(r) 
            love.graphics.setColor(0, 0, 0xff) -- blue
            love.graphics.line(0, 0, x1, y1)
        end
    end
    

    enter image description here