Skip to content

Instantly share code, notes, and snippets.

@abeldantas
Last active October 12, 2016 18:15
Show Gist options
  • Save abeldantas/43b1a6655117e0e17d0fbfdaccff519b to your computer and use it in GitHub Desktop.
Save abeldantas/43b1a6655117e0e17d0fbfdaccff519b to your computer and use it in GitHub Desktop.
Ellipse animation in LÖVE lua
function love.load()
-- Comet, is going to move around the Sun
comet = {}
comet.x = 0
comet.y = 0
-- These are 'a' and 'b' in the ellipse formula, think aphelion and perihelion
comet.trajectoryHeight = 40
comet.trajectoryWidth = 120
comet.timeItTakesToGoAroundTheSun = 3 -- 3 seconds, pretty fast
comet.timeSinceBeginning = 0
-- Origin (Sun)
sun = {}
sun.x = love.graphics.getWidth()/2
sun.y = love.graphics.getHeight()/2
end
function love.update(dt)
-- Increment the time since beginning variable, this is used to know how long it has been since the animation/movement started
comet.timeSinceBeginning = comet.timeSinceBeginning + dt
-- Calculate and assign the position of the comet
positionInEllipse = LerpEllipse(comet.trajectoryWidth, comet.trajectoryHeight, comet.timeSinceBeginning, sun, comet.timeItTakesToGoAroundTheSun )
comet.x = positionInEllipse.x
comet.y = positionInEllipse.y
end
function love.draw()
-- Draw yellow point (Sun)
love.graphics.setColor(255, 155, 0, 255)
love.graphics.circle("fill", sun.x, sun.y, 4, 4)
-- Draw blue point (comet)
love.graphics.setColor(60, 60, 255, 255)
love.graphics.circle("fill", comet.x, comet.y, 1, 4)
end
--- AUXILLIARY FUNCTIONS ---
-- Lerp Ellipse gives you the x and y position for something moving along an ellipse
-- 'a' and 'b' are the 2 axis of the ellipse
-- t is the time that has passed since the animation/movement has started
-- o is the central point around which the ellipse is centered, needs to have x and y
-- d is the duration of the whole movement/animation
function LerpEllipse(a,b,t,o,d)
position = {}
position.x = o.x + (a*math.cos((t/d) * math.pi*2))
position.y = o.y + (b*math.sin((t/d) * math.pi*2))
return position
end
-- To draw ellipses with rotation we need more math
-- x = a*cos(t)*cos(angle) - b*sin(t)*sin(angle)
-- y = a*cos(t)*sin(angle) + b*sin(t)*cos(angle)
--
-- To try out in wolfram alpha:
-- having a = 20; b = 120; rotation angle = pi/8
-- put the line bellow in wolfram alpha and you will see a rotated ellipse
-- x= 20*cos(t)*cos(pi/8)-120*sin(t)*sin(pi/8), y=20*cos(t)*sin(pi/8)+120*sin(t)*cos(pi/8)
@abeldantas
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment