I'm trying to make a simulation of a spring.
It is almost working, except that the spring skews about 2 pixels downward every oscillation. Anyone want to point out what is wrong?
function load()
ball={}
ball.y=50
ball.v=0
gravity=30
spring={}
spring.y=200
spring.top=200
spring.k=200
end
function keypressed(key)
if key == love.key_tab then
love.system.restart()
end
end
function update(dt)
--local dt=dt*5
ball.v=ball.v+gravity*dt
ball.y=ball.y+ball.v*dt
if ball.y>=spring.k then
spring.y=ball.y
ball.v=ball.v-(spring.k-spring.top)*dt
spring.top=spring.top-ball.v*dt
if spring.top>200 then
spring.top=200
end
end
end
function draw()
love.graphics.setColor(0,255,0)
love.graphics.rectangle(love.draw_fill,85,spring.y,30,spring.top)
love.graphics.setColor(255,0,0)
love.graphics.circle(love.draw_fill,100,ball.y,10)
end
Last edited by TechnoCat on Tue Aug 04, 2009 12:20 am, edited 1 time in total.
if ball.y>=spring.k then
spring.y=ball.y
ball.v=ball.v-(spring.k-spring.top)*dt
spring.top=spring.top-ball.v*dt
if spring.top>200 then
spring.top=200
end
end
if ball.y>=spring.k then
spring.y=ball.y
spring.top=spring.top-ball.v*dt
ball.v=ball.v-(spring.k-spring.top)*dt
end
ball.v needs to be updated after i use it to update spring.top. Otherwise the ball.v I used to calculate the new spring.top will be the next iterations velocity and not the current one.
I also didn't need to check if it was 200 or not anymore because it should function correctly now.