Hello,
I thought I might share this code from my game. While it’s not a class for scroll boxes and isn’t individual boxes, it’s the physics in this code that is valuable. Other scroll box classes have had clumsy scrolling physics, so here’s some code to improve it: (you may have to tweak with the numbers to get it working better)
function setup()
x = 0
vel = 0
friction = .95
width = 1500
elasticity = 1.3
scrolling = false
elastising = false
xAvgs = {}
end
function draw()
--output.clear()
background(40, 40, 50)
vel = vel * friction
x = x + vel
if scrolling == false then
if x >= 0 then
vel = vel / (elasticity*elasticity)
if vel <= 1 or elastising then
elastising = true
vel = -x / (elasticity * 10)
end
elseif x-WIDTH <= -width then
vel = vel / (elasticity*elasticity)
if vel >= -1 or elastising then
elastising = true
vel = ((-width+WIDTH)-x) / (elasticity * 10)
end
end
end
pushMatrix()
translate(x,0)
pushStyle()
fill(0, 92, 255, 255)
rect(0,0,width,HEIGHT)
popStyle()
pushStyle()
fill(255, 255, 255, 255)
for i = 0,width/100-1 do
text(i,i*100,HEIGHT/2)
end
popStyle()
popMatrix()
end
function touched(t)
if t.state == ENDED or t.state == CANCELLED then
--vel = t.deltaX
local xTotal = 0
local numAvg = 10
for i = 1,numAvg do
xTotal = xTotal + (xAvgs[i] or xAvgs[#xAvgs])
end
vel = xTotal / numAvg
xAvgs = {}
scrolling = false
elseif t.state == MOVING or t.state == BEGAN then
elastising = false
vel = 0
table.insert(xAvgs,t.deltaX)
x = x + t.deltaX
scrolling = true
end
end
Thanks! Let me know if you have any improvement.