Skip to content

Instantly share code, notes, and snippets.

@EngineerSmith
Last active January 2, 2020 21:54
Show Gist options
  • Save EngineerSmith/fb9ed238eae264ab5b4586d1894aa326 to your computer and use it in GitHub Desktop.
Save EngineerSmith/fb9ed238eae264ab5b4586d1894aa326 to your computer and use it in GitHub Desktop.
Simple scrolling "mountain range" for Löve2d
local train = {}
train.__index = train
local lg, lm = love.graphics, love.math
local MAXY = 1000
-- We use the previous value so that it doesn't get too crazy looking
-- Will need better generation which min and max so it doesn't go up or down forever
local function generateValue(previous) return (lm.random(20)-10)*2+previous*0.25 end
local function addBase(tbl, back)
table.insert(tbl, back)
table.insert(tbl, MAXY)
table.insert(tbl, tbl[1]) --Get the current X of the front
table.insert(tbl, MAXY)
end
local function removeBase(tbl)
for i = 1, 4 do table.remove(tbl, #tbl) end --Remove the last 4 values
end
-- Generates a line with different Y values which moves towards the right
-- train:new(200, 10, 20)
function train:new(length, peaks, speed)
local o = {}
setmetatable(o, self)
o.length = length or error("Train requires length")
peaks = peaks or error("Train requires peaks")
o.speed = speed or error("Train requires speed")
o.deltaX = 0
o.distance = length / peaks
o.distanceTraveled = o.distance -- So that we have 1 vertex that extends past the distance
o.vertices = {}
local previousValue = 0
for i = -o.distance, length+o.distance*2, o.distance do
table.insert(o.vertices, i) --X
previousValue = generateValue(previousValue)
table.insert(o.vertices, previousValue) --Y
end
addBase(o.vertices, length+o.distance)
--Make triangles due to shape being concave for fill draw
o.triangles = lm.triangulate(o.vertices)
return o
end
function train:update(dt)
self.deltaX = self.deltaX + self.speed * dt
if self.deltaX >= self.distanceTraveled then
self.distanceTraveled = self.distanceTraveled + self.distance
for i = 1, 2 do table.remove(self.vertices, 1) end --Remove the Front
removeBase(self.vertices) --Remove base to allow new values
--Add new back
table.insert(self.vertices, self.length + self.distanceTraveled)
table.insert(self.vertices, generateValue(self.vertices[#self.vertices-1])) -- -1 here will get the previous vertex Y
--Add base back
addBase(self.vertices, self.length+self.distanceTraveled)
self.triangles = lm.triangulate(self.vertices)
end
end
function train:draw(x, y, mode)
mode = mode or "fill"
lg.push()
lg.translate(x - self.deltaX, y)
if mode == "fill" then --Fill cannot draw our concave shape so it has to use triangles
for _, v in ipairs(self.triangles) do
lg.polygon(mode, v)
end
else
lg.polygon("line", self.vertices) --Line can handle the concave shape
end
lg.pop()
end
return train
@EngineerSmith
Copy link
Author

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