I am trying to create a simulation of balls dropping down a peg board, like this example:
ttps://www.youtube.com/watch?v=AUSKTk9ENzg
I have managed to create the parts of the code necessary to spawn in the pegs and the balls, and the balls successfully bounce down the peg board and are removed when they collide with a counting grid at the bottom.
However, in order to extract useful data from this simulation I need to count the number of balls that hit each interval on the grid. I have tried store this data by creating an empty table and setting the collision detection function to count collisions in each interval, but it doesn’t seem to work at the moment.
Ultimately, I would like to display this information in a bar chart, so any advice on implementing that would also be appreciated.
Relevant parts of the code below, I hope it’s vaguely clear what I’m trying to achieve… Thanks for any help.
local screenW, screenH, halfW = display.contentWidth, display.contentHeight, display.contentWidth\*0.5 -- Spacing parameter spacing = 45 -- Create pins based on separation parameter for i = 1,25 do pins = 0 for j = 1,25 do pins =pins+1 if pins \< (i) then if i\>2 then local pin = display.newCircle((halfW-(spacing/2)\*(i)+((j)\*spacing)), (i)\*(spacing/2)+118,spacing\*2/40) physics.addBody( pin, "static", { friction=0.0}) end end end end -- Setting position of counting intervals for i = 1,25 do countxpos[i] = (halfW-(spacing/2)\*(25)+((i)\*spacing))+spacing/2 end local countvals = { [1] = 0, [2] = 0, [3] = 0, [4] = 0, [5] = 0, [6] = 0, [7] = 0, [8] = 0, [9] = 0, [10] = 0, [11] = 0, [12] = 0, [13] = 0, [14] = 0, [15] = 0, [16] = 0, [17] = 0, [18] = 0, [19] = 0, [20] = 0, [21] = 0, [22] = 0, [23] = 0, } -- Function to spawn balls function newBall(x,y,radius) spacing = 45 radius = spacing\*4/20 local ball = display.newCircle(math.random(501,529),150,radius) ball.class = "ball" physics.addBody(ball,"dynamic",{radius=radius,density=5.0, friction=0.0, bounce=0.45 }) ball.gravityScale = 4 -- function to handle the collision on the ball and counting function ball:collision(e) if (e.other.class == "catcher") then for j=1,23 do if ball.x \> countxpos[j] and ball.x \< countxpos[j+1] then countvals[j]= countvals[j]+1 end end timer.performWithDelay(1, function() -- remove the ball display.remove(ball) end, 1) end -- always return true because we have handled the collision return true end -- attach a collision listener to the ball ball:addEventListener("collision",ball) return ball end -- function makeGraph() for i= 1,23 do local graph = display.newRect( countxpos[1], 25\*(spacing/2)+70, spacing, 20\*countvals[i] ) graph:setFillColor( 0.5 ) end end function timer1() newBall() end physics.start() local spawnTable = {} local graphTable = {} for i=1,1 do spawnTable[i] = timer.performWithDelay(1500,timer1,10) graphTable[i] = makeGraph() end for k, v in pairs( countvals ) do print(k, v) end