Tutorial - Physical Collisions And Forces

We will now enhance the world created in the previous tutorial, in order to apply forces to bodies and detect collisions between them

Collision Detection behaviour

In OnInit() method, we now add the 'collision-detection' behavior. This will make the callback method OnCollision(list collisions) method called upon collisions

world.addBehavior("collision-detection") // OnCollision will be called upon collision

OnUpdate() : adding forces

First we get from the world all bodies created with label 'ball'. Here it will be all bodies, but you can use these function to retrieve specific groups of bodies or even all world bodies if you don't specify which label
Then we pick a random body. the property length of a list or of a one dimensional array gives the number of objects it contains
Then we just apply a random force to that body

method void OnUpdate() { list bodies = world.findBodies("ball") // find all bodies with label 'ball' in world. Here it will be all bodies object body=bodies[rndInt(bodies.length - 1) ] // pick one random body body.applyForce(.0025-rnd(.005),.08-rnd(.24)) // apply random force }

OnCollision() callback

Because we added 'collision-detection' behavior to the world, at each frame, if one or more collisions happened during last frame, the OnCollision method will be called
This callback provides as parameter a list of collisions (that may have only one element)
So, we iterate through the list and for each object of the list, we have as properties two objects bodyA and bodyB that are the two objects involved in that particular collision
Then it is just a matter of setting a smaller scale for the first one, and a bigger for the second, not forgetting to check that scales stay in reasonable limits

method void OnCollision(list collisions) { foreach object c in collisions // loop through all collisions if (c.bodyA.label == "ball") // c is the collision, it has 2 object bodyA and BodyB that are the two colliding bodies. if (c.bodyA.getScale() > 0.35) // check the scale c.bodyA.setScale(c.bodyA.getScale()*0.99); // scale dowwn if not too small endif endif if (c.bodyB.label == "ball") // with second boy scale up if not too small if (c.bodyB.getScale() < 4) c.bodyB.setScale(c.bodyB.getScale()*1.02) endif endif next }

You can try the code in TUTO-PHYSIC-COLLISIONS project on the Guest Account
You can find reference of the functions used in the Documentation