Kalimah
Kalimah

Reputation: 11437

physics.addbody() does not work inside a loop in corona

I am trying to add multiple rectangles in one hit through a loop and here is my code:

for i=1,7,1 do
   rec = rectangles.createRoundedRect(left, top, 100, 18, 6)
  physics.addBody(rec , "static", { density = 1.0, friction = 0.0, bounce = 0.2 } )
  left = left + 50
  top = top - 35
end

The rectangles are added successfully however they are not treated as bodies (i.e other bodies do not collide with them)

What's wrong with the code?

Upvotes: 0

Views: 465

Answers (3)

Kalimah
Kalimah

Reputation: 11437

I solve the issue I was using object:translate() to move objects while I was suppose to use object:setLinearVelocity()

Upvotes: 0

pookzilla
pookzilla

Reputation: 406

There might be several causes for your problem. Verify that a) the boxes are indeed not added to the physics engine (by enabling hybrid physics mode with physics.setDrawMode("hybrid")). It might be that the boxes are there but you're having issues with your object filters (see http://developer.coronalabs.com/forum/2010/10/25/collision-filters-helper-chart) b) rectangles.createRoundedRect (which I presume is your own function) isn't adding the created objects to a group that isn't the same group as your other objects (if any). Corona physics do not play well among objects created across groups.

Upvotes: 0

Jutanium
Jutanium

Reputation: 421

(I think) it's because you keep adding the same rec to the physics engine over and over. Try this:

rec = {}
for i=1,7,1 do
 rec[i] = rectangles.createRoundedRect(left, top, 100, 18, 6)
 physics.addBody(rec[i] , "static", { density = 1.0, friction = 0.0, bounce = 0.2 } )
 left = left + 50
 top = top - 35
end

And see if it works.

Upvotes: 1

Related Questions