Using E.g. Topleftalign() On A Physics Body Only Applies To Its Appearance, Not Its Body... Help?

I’m using topLeftAlign() on a physics body to apply a rotation angle from a data source, and this displays fine with the image – however, the actual physics body is still the old unrotated version so collisions are completely off. It even seems to suggest as much in the Corona help.

 

Is there a workaround to have the physics body be at the position the image displays?

Hi Philipp,

Physics bodies are always center-oriented, and the “reference point” applies to the image aspect only.

 

One workaround would be to use a little routine that gets the “new center point” of a rotated image using “localToContent()”, then repositioning the object based on this point (and the rotation you desire):

 

[lua]

local rectOrig = display.newRect(200,400,80,200) ; rectOrig.alpha = 0.5

 

local rect = display.newRect(200,400,80,200)

physics.addBody( rect, “static” )

–rotate the rect based on the top-left reference point

rect:setReferencePoint(display.TopLeftReferencePoint)

rect.rotation = -30

–get the “content center point” after rotation

local rectContentX, rectContentY = rect:localToContent( 0,0 )

–temporarily restore object to 0 rotation and center reference point

rect.rotation = 0

rect:setReferencePoint(display.CenterReferencePoint)

–move it to the values determined above

rect.x, rect.y = rectContentX, rectContentY

–rotate it back to the angle you want

rect.rotation = -30

–object and physics body are now synched around center reference point!

[/lua]

 

Hope this helps,

Brent

*snif* Works like a charm!

 

Thanks!

Hi Philipp,

Physics bodies are always center-oriented, and the “reference point” applies to the image aspect only.

 

One workaround would be to use a little routine that gets the “new center point” of a rotated image using “localToContent()”, then repositioning the object based on this point (and the rotation you desire):

 

[lua]

local rectOrig = display.newRect(200,400,80,200) ; rectOrig.alpha = 0.5

 

local rect = display.newRect(200,400,80,200)

physics.addBody( rect, “static” )

–rotate the rect based on the top-left reference point

rect:setReferencePoint(display.TopLeftReferencePoint)

rect.rotation = -30

–get the “content center point” after rotation

local rectContentX, rectContentY = rect:localToContent( 0,0 )

–temporarily restore object to 0 rotation and center reference point

rect.rotation = 0

rect:setReferencePoint(display.CenterReferencePoint)

–move it to the values determined above

rect.x, rect.y = rectContentX, rectContentY

–rotate it back to the angle you want

rect.rotation = -30

–object and physics body are now synched around center reference point!

[/lua]

 

Hope this helps,

Brent

*snif* Works like a charm!

 

Thanks!