2015年4月29日 星期三

[Corona SDK] How can we decide if the collision will happen or not for each object?

In [Corona SDK] How to detect the collision for physical objects - using Global Collision, we find that all objects will collide with each other.
We can then decide how to deal with the collision in function onGlobalCollision().
What if we wish that fruit1 and fruit2 will not collide with each other?
For it, we need to add the parameter filter, as shown below:
local main = display.newImage( "main.png", 160, 240 )
local mainCollisionFilter = { categoryBits=2, maskBits=1023 } 
physics.addBody( main, { density = 1.0, friction = 0.3, bounce = 0.2 , filter=mainCollisionFilter} )
main.myName = "main"

local fruit1 = display.newImage( "fruit.png", 100, 120 )
local fruit1CollisionFilter = { categoryBits=4, maskBits=2 } 
physics.addBody( fruit1, { density = 1.0, friction = 0.3, bounce = 0.2, filter=fruit1CollisionFilter} )
fruit1.myName = "fruit1"

local fruit2 = display.newImage( "fruit.png", 300, 220 )
local fruit2CollisionFilter = { categoryBits=8, maskBits=6 } 
physics.addBody( fruit2, { density = 1.0, friction = 0.3, bounce = 0.2, filter=fruit2CollisionFilter } )
fruit2.myName = "fruit2"

local fruit3 = display.newImage( "fruit.png", 300, 220 )
physics.addBody( fruit3, { density = 1.0, friction = 0.3, bounce = 0.2 } )
fruit3.myName = "fruit3"
The parameter categoryBits is used to set the category of that object.
Basically, this value will be unique for each object if we want to distinguish them.
categoryBits is set in bit level since it will cooperate with maskBits.
Of course, we can set the same categoryBits for different objects, if we want them to have similar behaviors. 
categoryBits can also be set to 1 for multiple bits, such as 7.
The final behavior will be decided by the result of mask operation with maskBits.
We can show the filter setting of above codes by the chart:
For fruit3, it does not specify the parameter filter. Its default setting will be { categoryBits=1, maskBits=1023 }, which means that it will collide with all other objects.
It there may have some objects without filter setting, we'd better set categoryBits start from 2 for those object with filter.
Besides, in the example, the maskBits for fruit2 is 6. It means that it wish to collide with main and fruit1.
However, the maskBits for fruit1 is 2, which means that it does not want to collide with fruit2.
The mask operation is the result of AND for all values.
fruit1 will not collide with fruit2 in the end.

沒有留言:

張貼留言