限制加速度计的倾斜事件运动。

如何限制加速度计 onTilt 事件的移动距离为 30 像素左侧、右侧、上侧和下侧。这段代码允许根据加速度计倾斜移动,但移动距离没有限制。

local screenGroup = self.view
local bg2  = display.newImage ("bg2.png")
bg2.x = display.contentWidth / 2;
bg2.y = 200

local tiltSpeed = 30;
local motionx = 0;
local motiony = 0;
local rotation = 0;

delta = -50/180*math.pi
cos_delta, sin_delta = math.cos(delta), math.sin(delta)

local function onTilt(event)
    motionx = tiltSpeed * event.xGravity
    motiony = tiltSpeed * (cos_delta*event.yGravity + sin_delta*event.zGravity)

    -- 限制移动距离
    if bg2.x + motionx > display.contentWidth - 30 then
        motionx = display.contentWidth - bg2.x - 30
    elseif bg2.x + motionx < 30 then
        motionx = 30 - bg2.x
    end
    if bg2.y - motiony < 30 then
        motiony = bg2.y - 30
    elseif bg2.y - motiony > display.contentHeight - 30 then
        motiony = bg2.y - display.contentHeight + 30
    end
end

local function moveBg2 (event)
    bg2.x = motionx + bg2.x ;
    bg2.y = bg2.y - motiony;
end
Runtime:addEventListener("enterFrame", moveBg2)
Runtime:addEventListener("accelerometer", onTilt)
点赞
用户2633423
用户2633423

问题不是很清楚,但我猜这样做就可以了:

local function onTilt(event)
    motionx = tiltSpeed * event.xGravity
    motiony = tiltSpeed * (cos_delta*event.yGravity + sin_delta*event.zGravity)
    if motionx < -30 then
        motionx = -30
    elseif motionx > 30 then
        motionx = 30
    end
    if motiony < -30 then
        motiony = -30
    elseif motiony > 30 then
        motiony = 30
    end
end
2013-09-28 19:07:38