Skip to content

Instantly share code, notes, and snippets.

@madebyjeffrey
Created July 31, 2011 20:21
Show Gist options
  • Save madebyjeffrey/1117173 to your computer and use it in GitHub Desktop.
Save madebyjeffrey/1117173 to your computer and use it in GitHub Desktop.
require("string")
state = {}
function love.load()
state.size = { cx = love.graphics.getWidth(), cy = love.graphics.getHeight() }
-- ball is a position, a mass, and a velocity
state.ball = { position = { x = state.size.cx / 2, y = state.size.cy / 2 },
mass = 50,
velocity = { x = 0, y = 0 } }
borderColour = { 255, 255, 255, 255 }
ballColour = { 255, 0, 0, 255 }
end
function love.update(dt)
-- note that this function doesn't do exactly what it needs to do yet, must be worked out more
local forces = { {x = 0, y = -9.81 / state.ball.mass} }
state.ball = ballNext(state.ball, forces, dt)
print(string.format("update %f", dt))
print(string.format("ball: %f, %f", state.ball.position.x, state.ball.position.y))
end
function love.draw()
-- love.graphics.print('Hello World!', 400, 300)
-- draw the border
love.graphics.setColor(borderColour)
love.graphics.rectangle("line", 0.5, 0.5, state.size.cx, state.size.cy)
-- draw the ball
love.graphics.setColor(ballColour)
love.graphics.circle("fill", state.ball.position.x + 0.5, state.ball.position.y + 0.5, 10)
end
function love.keypressed(key, unicode)
if (key == "escape") then
love.event.push('q')
end
end
function ballNext(ball, forces, dt)
-- add new velocities together
sum = { x = 0, y = 0 }
-- ipairs returns an iterator - for indexed tables
-- pairs is for key-pair tables
for _, f in ipairs(forces) do
sum.x = sum.x + f.x/ball.mass * dt
sum.y = sum.y + f.y/ball.mass * dt
end
ball2 = deepcopy(ball)
ball2.velocity.x = ball2.velocity.x + sum.x
ball2.velocity.y = ball2.velocity.y + sum.y
ball2.position.x = ball2.position.x + ball2.velocity.x * dt
ball2.position.y = ball2.position.y + ball2.velocity.y * dt
return ball2
end
-- stolen from http://lua-users.org/wiki/CopyTable
function deepcopy(object)
local lookup_table = {}
local function _copy(object)
if type(object) ~= "table" then
return object
elseif lookup_table[object] then
return lookup_table[object]
end
local new_table = {}
lookup_table[object] = new_table
for index, value in pairs(object) do
new_table[_copy(index)] = _copy(value)
end
return setmetatable(new_table, getmetatable(object))
end
return _copy(object)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment