First of all thanks for such a wonderful app and especial thanks to Ignatz for his tutorials, without which I wouldn’t have got anywhere, but can anyone explain the problem with the polygon collision code below. Sometimes it seems to work fine, while at other times it generates an error saying ‘attempt to index field, a nil value’
Has anyone got any thoughts because I’m a bit stumped!
--- poly2
function setup()
physics.iterations(20,20)
poly={} -- an empty table to fill with the polygons created by touches
loop=0 -- the number of polygons, initially zero
parameter.number("restitution",0,1,1)
parameter.integer("min_length",10,100,20)
parameter.integer("max_length",15,200,30)
parameter.integer("min_edges",3,50,3)
parameter.integer("max_edges",3,50,10)
parameter.number("friction",0,1,0)
parameter.integer("side_variation_factor",0,20)
w1 = physics.body(EDGE,vec2(0,0),vec2(WIDTH,0),1)
w2 = physics.body(EDGE,vec2(0,0),vec2(0,HEIGHT),1)
w3 = physics.body(EDGE,vec2(WIDTH,0),vec2(WIDTH,HEIGHT),1)
w4 = physics.body(EDGE,vec2(0,HEIGHT),vec2(WIDTH,HEIGHT),1)
end
function touched(touch)
if touch.state==ENDED then loop = loop + 1
vx=touch.deltaX*50
vy=touch.deltaY*50
makepoly(touch.x,touch.y,vx,vy)
end
end
function collide(contact)
if contact.state == BEGAN then
ca=contact.bodyA.info
cb=contact.bodyB.info
if contact.bodyA.mass~=0 and contact.bodyB.mass~=0 then
print("Hit between "..ca.." and "..cb)
sound(SOUND_EXPLODE, math.random(2500,2510))
poly[ca].kill='y'
poly[cb].kill='y'
end
end
end
function makepoly(x,y,vx,vy)
count=math.random(min_edges,max_edges)
r=math.random(min_length,max_length)
a=0
d=(2*math.pi)/count
points={}
for i=1,count do
v=vec2(r,0):rotate(a) + vec2(math.random(- side_variation_factor,side_variation_factor),math.random(-side_variation_factor,side_variation_factor))
a=a+d
table.insert(points,v)
end
--the code below picks up the table of vec2s and makes a physics body from them
poly[loop]=physics.body(POLYGON,unpack(points))
poly[loop].x=x
poly[loop].y=y
poly[loop].restitution=restitution
poly[loop].friction=friction
poly[loop].color=color(math.random(50,255),math.random(50,255),math.random(50,255),255)
poly[loop].vertices=points
poly[loop].sleepingAllowed=false
poly[loop].interpolate=true
poly[loop].angularDamping=1.5
poly[loop].linearDamping=0
poly[loop].linearVelocity=vec2(vx,vy)
poly[loop].info=loop
poly[loop].kill='n'
end
function draw()
background(4, 4, 4, 255)
physics.gravity(Gravity)
polylines()
end
function polylines()
for j,v in pairs(poly) do
if poly[j].kill=='y' then
poly[j]:destroy()
poly[j]=nil
table.remove(poly,j)
else
pushMatrix()
pushStyle()
poly[j].restitution=restitution
translate(poly[j].x,poly[j].y)
rotate(poly[j].angle)
strokeWidth(2)
stroke(poly[j].color)
points=poly[j].vertices
for m=1,#points do
a=points[m]
b=points[(m%#points)+1]
line(a.x,a.y,b.x,b.y)
end
popStyle()
popMatrix()
end
end
end