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.
Something like this should work (this was typed from memory so there may be errors):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| 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) |
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.
To detect when a finger has been lifted off the screen you have to another button phase. Add this to you button function.
1
| elseif event.phase == "ended" then |
Just add an "ended" event to the onScreenTouch function like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
| 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 |
@Khaodik and @calebr2048
Thanks.
views:1342 update:2011/9/28 9:01:40