Adding Physics to Buttons

Hello,
 
Ive made a button that reacts to physics and can be thrown around the screen using the gameUI.lua file you can download.
 
The issue is when I add physics to it the “hitbox” (sorry I wasnt sure what else to call it) would become offset, I was wondering if there was any way of making the “hitbox” act normal again?
 
Thanks.

crabBtn = widget.newButton{ width = 36, height = 36, defaultFile = "crabIcon.png", overFile = "crabIcon.png", label = "Ship Game", onEvent = crabIconHandler } physics.addBody(crabBtn) crabBtn:addEventListener("touch", gameUI.dragBody)

I have also included a photo of the broken button “Ship Game” and what I want it to do. The other icon shown in the photo is just an image with the same physics and gameUI added. I dont want the button to sink in the ground.

Hi @hayful59,

At a general level, widget.newButton() creates a display group which contains the various button elements, and physics should rarely/never be added to an entire display group. That being said, you may be able to re-orient the physics “hitbox” by setting an offset rectangular body on the button, instead of using the “default” trace. See this guide for details:

https://docs.coronalabs.com/guide/physics/physicsBodies/index.html#offsetangled-rectangular-bodies

Best regards,

Brent

After looking at the page Brent suggested, I came up with this. I just made a custom shape of a square, and set the crab button to that instead.

[lua]

crabBtn = widget.newButton{
 width = 36,
 height = 36,
 defaultFile = “crabIcon.png”,
 overFile = “crabIcon.png”,
 label = “Ship Game”,
 onEvent = crabIconHandler
}
local crabShape = { 0,0, 36,0, 36,36, 0,36 } – custom square shape
physics.addBody(crabBtn, “dynamic”, { density=3.0, friction=0.5, bounce=0.2, shape=crabShape })
crabBtn:addEventListener(“touch”, gameUI.dragBody)​

[/lua]

Hi @hayful59,

At a general level, widget.newButton() creates a display group which contains the various button elements, and physics should rarely/never be added to an entire display group. That being said, you may be able to re-orient the physics “hitbox” by setting an offset rectangular body on the button, instead of using the “default” trace. See this guide for details:

https://docs.coronalabs.com/guide/physics/physicsBodies/index.html#offsetangled-rectangular-bodies

Best regards,

Brent

After looking at the page Brent suggested, I came up with this. I just made a custom shape of a square, and set the crab button to that instead.

[lua]

crabBtn = widget.newButton{
 width = 36,
 height = 36,
 defaultFile = “crabIcon.png”,
 overFile = “crabIcon.png”,
 label = “Ship Game”,
 onEvent = crabIconHandler
}
local crabShape = { 0,0, 36,0, 36,36, 0,36 } – custom square shape
physics.addBody(crabBtn, “dynamic”, { density=3.0, friction=0.5, bounce=0.2, shape=crabShape })
crabBtn:addEventListener(“touch”, gameUI.dragBody)​

[/lua]