Press, release and physics

Hi.

Could you give me some advice on how to do the following? :

  • User taps screen and keeps finger on screen

  • This moves a circle in an upward trajectory with acceleration

  • User takes finger off screen

  • This “releases” the circle to act under gravity

  • Circle lands on a “floor” and decelerates to a stop

It’s a bit of a vague description but any tips would be appreciated. [import]uid: 64736 topic_id: 12722 reply_id: 312722[/import]

Something like this should work (this was typed from memory so there may be errors):[lua]local physics = require(“physics”)

local H = display.contentHeight
local W = display.contentWidth
local centerX = W * 0.5
local centerY = H * 0.5

physics.start()
physics.setGravity(0,4)

local floor = display.newRect(0, 0, W, 50)
floor.x = centerX, floor.y = H
physics.addBody(floor, “static”, {density=1.0, friction=0.5, bounce=0.2})
local circle = display.newCircle(centerX,100,50)
physics.addBody(circle, “dynamic”, {density=1.0, friction=0.5, bounce=0.2, radius=50})

local onScreenTouch = function(event)
if event.phase == “began” then
– You can play with the values to get the reaction you want
circle:applyForce(
-4, 0,
circle.x, circle.y)
end
end

Runtime:addEventListener(“touch”, onScreenTouch)[/lua] [import]uid: 27965 topic_id: 12722 reply_id: 46649[/import]

Nice one, thanks.

I’m playing around with changing the gravity after the user has stopped touching the screen and it seems to work. I’m using a second tap to replicate a fingerOff event.

What I can’t work out is how to detect a “fingerOffScreen” event. [import]uid: 64736 topic_id: 12722 reply_id: 46651[/import]

To detect when a finger has been lifted off the screen you have to another button phase. Add this to you button function.
[lua]    elseif event.phase == “ended” then [import]uid: 17138 topic_id: 12722 reply_id: 46664[/import]

Just add an “ended” event to the onScreenTouch function like this:

[lua]local onScreenTouch = function(event)
– This checks when the screen is touched
if event.phase == “began” then
– You can play with the values to get the reaction you want
circle:applyForce(
-4, 0,
circle.x, circle.y)
– This checks when the touch has ended
elseif event.phase == “ended” then
– Put modified gravity settings here
physics.setGravity(0,10)
end
end[/lua]
[import]uid: 27965 topic_id: 12722 reply_id: 46666[/import]

@Khaodik and @calebr2048

Thanks. [import]uid: 64736 topic_id: 12722 reply_id: 46674[/import]