axmol/samples/Lua/TestLua/Resources/luaScript/AccelerometerTest/AccelerometerTest.lua

68 lines
1.7 KiB
Lua
Raw Normal View History

2013-05-24 11:42:27 +08:00
local function AccelerometerMainLayer()
local function title()
return "AccelerometerTest"
end
local pLayer = cc.Layer:create()
2013-05-24 11:42:27 +08:00
pLayer:setAccelerometerEnabled(true)
local pLabel = cc.LabelTTF:create(title(), "Arial", 32)
2013-05-24 11:42:27 +08:00
pLayer:addChild(pLabel, 1)
pLabel:setPosition( cc.p(VisibleRect:center().x, VisibleRect:top().y - 50) )
2013-05-24 11:42:27 +08:00
local pBall = cc.Sprite:create("Images/ball.png")
pBall:setPosition(cc.p(VisibleRect:center().x, VisibleRect:center().y))
2013-05-24 11:42:27 +08:00
pLayer:addChild(pBall)
pBall:retain()
local function didAccelerate(x,y,z,timestamp)
local pDir = cc.Director:getInstance()
2013-05-24 11:42:27 +08:00
if nil == pBall then
return
end
local szBall = pBall:getContentSize()
local ptNowX,ptNowY = pBall:getPosition()
2013-05-24 11:42:27 +08:00
2013-09-18 16:44:05 +08:00
ptNowX = ptNowX - x
ptNowY = ptNowY - y
2013-05-24 11:42:27 +08:00
2013-09-18 16:44:05 +08:00
local minX = math.floor(VisibleRect:left().x + szBall.width / 2.0)
local maxX = math.floor(VisibleRect:right().x - szBall.width / 2.0)
if ptNowX < minX then
ptNowX = minX
elseif ptNowX > maxX then
ptNowX = maxX
2013-05-24 11:42:27 +08:00
end
2013-09-18 16:44:05 +08:00
local minY = math.floor(VisibleRect:bottom().y + szBall.height / 2.0)
local maxY = math.floor(VisibleRect:top().y - szBall.height / 2.0)
if ptNowY < minY then
ptNowY = minY
elseif ptNowY > maxY then
ptNowY = maxY
2013-05-24 11:42:27 +08:00
end
2013-09-18 16:44:05 +08:00
pBall:setPosition(cc.p(ptNowX, ptNowY ))
2013-05-24 11:42:27 +08:00
end
pLayer:registerScriptAccelerateHandler(didAccelerate)
return pLayer
end
function AccelerometerMain()
cclog("AccelerometerMain")
local scene = cc.Scene:create()
2013-05-24 11:42:27 +08:00
scene:addChild(AccelerometerMainLayer())
scene:addChild(CreateBackMenuItem())
return scene
end