2015年4月13日 星期一

[Corona SDK] How to deal with collision of two objects with irregular shapes using physics.addBody()?

Below is a simple example for physical collision:
local physics = require( "physics" )
physics.start()

local sky = display.newImage( "bkg_clouds.png", 160, 195 )

local ground = display.newImage( "ground.png", 160, 445 )

physics.addBody( ground, "static", { friction=0.5, bounce=0.3 } )

local crate = display.newImage( "crate.png", 180, -50 )
crate.rotation = 5

physics.addBody( crate, { density=3.0, friction=0.5, bounce=0.3 } )
The pictures used are shown below:
bkg_clouds.png

crate.png

ground.png
The result after collision:

However, in real world, most objects are not in regular shape.
Let us modify crate.png and gound.png as below:
crate.png

ground.png
Check the result again:
It seems that the collision is as the result of before changing.
Why?

Actually, we can specify the shape of object in physics.addBody(), such as rectangular body, circular body, polygonal body, and so on.
Here we use the outline of the original object got from graphics.newOutline().
The codes are modified as below:
local physics = require( "physics" )
physics.start()

local sky = display.newImage( "bkg_clouds.png", 160, 195 )

local ground = display.newImage( "ground.png", 160, 445 )
local ground_outline = graphics.newOutline( 2, "ground.png" )
physics.addBody( ground, "static", { friction=0.5, bounce=0.3,outline=ground_outline } )


local crate = display.newImage( "crate.png", 180, -50 )
crate.rotation = 5
local image_outline = graphics.newOutline( 2, "crate.png" )
physics.addBody( crate, { density=0.2, friction=0.5, bounce=0.3,outline=image_outline} )
The first parameter of graphics.newOutline() is to specify the coarseness of the outline.
Let's check the result again:

沒有留言:

張貼留言