Skip to content

Instantly share code, notes, and snippets.

@TannerRogalsky
Created June 24, 2016 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TannerRogalsky/4c2834f3af1e122f73088c01aa646d29 to your computer and use it in GitHub Desktop.
Save TannerRogalsky/4c2834f3af1e122f73088c01aa646d29 to your computer and use it in GitHub Desktop.
Fake 2D Sphere Without A Shader
local function insertVertices(vertices, vert, ...)
if vert then
table.insert(vertices, vert)
insertVertices(vertices, ...)
end
end
local function createSphereVertex(radius, theta, phi, ox, oy)
local xb = math.cos(phi) * math.cos(theta)
local yb = math.sin(theta)
local x, y = radius * xb, radius * yb
local r = math.min(1, math.sqrt(xb * xb + yb * yb))
local f = (1 - math.sqrt(1 - r)) / r
local u = xb * f + ox
local v = yb * f + oy
return {x, y, u, v}
end
local function generateSphereVertices(radius, slices, stacks, ox, oy)
local pi, cos, sin = math.pi, math.cos, math.sin
local vertices = {}
for t=1,stacks do
local s = t - stacks / 2
local theta1 = (s - 1) / stacks * pi
local theta2 = s / stacks * pi
for p=1,slices do
local phi1 = (p - 1) / slices * pi
local phi2 = p / slices * pi
local v1 = createSphereVertex(radius, theta1, phi1, ox, oy)
local v2 = createSphereVertex(radius, theta1, phi2, ox, oy)
local v3 = createSphereVertex(radius, theta2, phi2, ox, oy)
local v4 = createSphereVertex(radius, theta2, phi1, ox, oy)
if( t == 1 ) then -- top cap
insertVertices(vertices, v1, v3, v4)
elseif( t == stacks ) then --end cap
insertVertices(vertices, v3, v1, v2)
else
insertVertices(vertices, v1, v2, v4)
insertVertices(vertices, v2, v3, v4)
end
end
end
return vertices
end
local RADIUS = 50
local NUM_VERTS = 40
function love.load()
sphere_mesh = g.newMesh(generateSphereVertices(RADIUS, NUM_VERTS, NUM_VERTS, 0, 0), 'triangles')
sphere_mesh:setTexture(texture)
end
function love.update(dt)
local time = love.timer.getTime()
sphere_mesh:setVertices(generateSphereVertices(RADIUS, NUM_VERTS, NUM_VERTS, time, time / 2))
end
function love.draw()
g.draw(sphere_mesh, 0, 0)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment