2013-05-24 11:42:27 +08:00
|
|
|
local function AccelerometerMainLayer()
|
|
|
|
|
2013-09-18 17:19:34 +08:00
|
|
|
local function title()
|
|
|
|
return "AccelerometerTest"
|
|
|
|
end
|
|
|
|
local layer = cc.Layer:create()
|
|
|
|
|
|
|
|
layer:setAccelerometerEnabled(true)
|
2013-05-24 11:42:27 +08:00
|
|
|
|
2013-09-18 17:19:34 +08:00
|
|
|
local label = cc.LabelTTF:create(title(), "Arial", 32)
|
|
|
|
layer:addChild(label, 1)
|
|
|
|
label:setPosition( cc.p(VisibleRect:center().x, VisibleRect:top().y - 50) )
|
2013-05-24 11:42:27 +08:00
|
|
|
|
2013-09-18 17:19:34 +08:00
|
|
|
local ball = cc.Sprite:create("Images/ball.png")
|
|
|
|
ball:setPosition(cc.p(VisibleRect:center().x, VisibleRect:center().y))
|
|
|
|
layer:addChild(ball)
|
|
|
|
|
|
|
|
ball:retain()
|
2013-05-24 11:42:27 +08:00
|
|
|
|
|
|
|
local function didAccelerate(x,y,z,timestamp)
|
|
|
|
|
2013-09-18 17:19:34 +08:00
|
|
|
if nil == ball then
|
|
|
|
return
|
|
|
|
end
|
|
|
|
|
2013-09-20 22:05:37 +08:00
|
|
|
local director = cc.Director:getInstance()
|
2013-09-18 17:19:34 +08:00
|
|
|
local szBall = ball:getContentSize()
|
|
|
|
local ptNowX,ptNowY = ball:getPosition()
|
2013-09-20 22:05:37 +08:00
|
|
|
local ptTemp = director:convertToUI(cc.p(ptNowX,ptNowY))
|
2013-05-24 11:42:27 +08:00
|
|
|
|
2013-09-20 22:05:37 +08:00
|
|
|
ptTemp.x = ptTemp.x + x * 9.81
|
|
|
|
ptTemp.y = ptTemp.y - y * 9.81
|
2013-05-24 11:42:27 +08:00
|
|
|
|
2013-09-20 22:05:37 +08:00
|
|
|
local ptNext = director:convertToGL(cc.p(ptTemp.x,ptTemp.y))
|
2013-05-24 11:42:27 +08:00
|
|
|
|
2013-09-18 17:19:34 +08:00
|
|
|
local minX = math.floor(VisibleRect:left().x + szBall.width / 2.0)
|
|
|
|
local maxX = math.floor(VisibleRect:right().x - szBall.width / 2.0)
|
2013-09-20 22:05:37 +08:00
|
|
|
if ptNext.x < minX then
|
|
|
|
ptNext.x = minX
|
|
|
|
elseif ptNext.x > maxX then
|
|
|
|
ptNext.x = maxX
|
2013-09-18 17:19:34 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
local minY = math.floor(VisibleRect:bottom().y + szBall.height / 2.0)
|
|
|
|
local maxY = math.floor(VisibleRect:top().y - szBall.height / 2.0)
|
2013-09-20 22:05:37 +08:00
|
|
|
if ptNext.y < minY then
|
|
|
|
ptNext.y = minY
|
|
|
|
elseif ptNext.y > maxY then
|
|
|
|
ptNext.y = maxY
|
2013-09-18 17:19:34 +08:00
|
|
|
end
|
|
|
|
|
2013-09-20 22:05:37 +08:00
|
|
|
ball:setPosition(cc.p(ptNext.x , ptNext.y))
|
2013-05-24 11:42:27 +08:00
|
|
|
end
|
|
|
|
|
2013-09-18 17:19:34 +08:00
|
|
|
layer:registerScriptAccelerateHandler(didAccelerate)
|
2013-05-24 11:42:27 +08:00
|
|
|
|
2013-09-18 17:19:34 +08:00
|
|
|
return layer
|
2013-05-24 11:42:27 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
function AccelerometerMain()
|
|
|
|
cclog("AccelerometerMain")
|
2013-08-20 13:44:37 +08:00
|
|
|
local scene = cc.Scene:create()
|
2013-05-24 11:42:27 +08:00
|
|
|
scene:addChild(AccelerometerMainLayer())
|
|
|
|
scene:addChild(CreateBackMenuItem())
|
|
|
|
return scene
|
|
|
|
end
|