The code below:
-
creates four static, linear physics objects around the four borders of the screen
-
creates three balls as dynamic physics objects and applies a linear impulse to each
The result is three bouncing balls, which are bouncing around the screen endlessly (as the friction is set to zero), including colliding with one another.
An alternative approach to implementing the same behaviour is to control the movement of the balls with code as opposed to physics forces/impulse. The code would run, for example, every frame and change the position of each ball according to a predetermined speed variable (ball1.x = ball1.x + ball1VelocityX etc.), and it would also check whether any of the balls have reached the border of the screen and in that case reverse the velocity of that ball, i.e. making the ball bounce off that wall.
My question is what the advantages and disadvantages are of these two different approaches for implementing a bouncing ball behaviour within the Corona SDK framework. The physics approach seems more natural to me but I wonder if there are problems with it, particularly in regards to collisions between the balls. The physics approach hands the control of the balls movement and collisions over to the physics engine. The alternative approach would retain more control over the balls movement, but perhaps that control is not necessary if the physics engine works well.
left = display.newLine(1, 1, 1, display.contentHeight-1) right = display.newLine(display.contentWidth-1, 1, display.contentWidth-1, display.contentHeight-1) bottom = display.newLine(1, display.contentHeight-1, display.contentWidth-1, display.contentHeight-1) top = display.newLine(1, 1, display.contentWidth-1, 1) physics.addBody(left, 'static', {density=1.0, friction=0, bounce=1}) physics.addBody(right, 'static', {density=1.0, friction=0, bounce=1}) physics.addBody(bottom, 'static', {density=1.0, friction=0, bounce=1}) physics.addBody(top, 'static', {density=1.0, friction=0, bounce=1}) ball1 = display.newCircle (100,100,32) physics.addBody(ball1, "dynamic", {density=1.0, friction=0, bounce=1, radius=32}) ball1:applyLinearImpulse(60,20,16,16) ball2 = display.newCircle (150,150,32) physics.addBody(ball2, "dynamic", {density=1.0, friction=0, bounce=1, radius=32}) ball1:applyLinearImpulse(60,20,16,16) ball3 = display.newCircle (200,200,32) physics.addBody(ball3, "dynamic", {density=1.0, friction=0, bounce=1, radius=32}) ball3:applyLinearImpulse(60,20,16,16)