0

我有一个呈现角色的组。它包含头部、手臂和身体的其他部位。我想为该组设置触摸监听器,这样当我触摸头部时,手臂和身体会做一些动作。我不想将触摸侦听器设置为仅头部,而是整个组。我将 name 设置为 head,并希望 event.other 可以工作(如碰撞),但事实并非如此。

你有什么解决办法吗?我的代码如下

local touchListener= function( event )
        if (event.phase=="began") then
            local group = event.target
            local head= group[1]
            local arms= group[2]
            local body= group[3]

            if( event.other.name == "head" ) then

            // do something here
            end
        end
return true
end
4

1 回答 1

0

您应该首先创建身体的那些特定部位。然后你应该为每个人添加触摸监听器。例如,您有名为“head”、“arms”和“body”的对象

head.id = "head"
arms.id = "arms"
body.id = "body"

head:addEventListener( "touch", touchHandler )
arms:addEventListener( "touch", touchHandler )
body:addEventListener( "touch", touchHandler )

-- Touch function here
    local function touchHandler( event )
        if event.phase == "began" then
            display.getCurrentStage():setFocus( event.target )
            event.target.isFocus = true 
        elseif event.target.isFocus then
            if event.phase == "moved" and not ( inBounds( event ) ) then
                display.getCurrentStage():setFocus( nil )
                event.target.isFocus = false
            elseif event.phase == "ended" then
                if event.id == "head" then
                  -- Do stuff for head
                elseif event.id == "arms" then
                  -- Do stuff for arms
                elseif event.id == "body" then
                  -- Do stuff for body
                end
                display.getCurrentStage():setFocus( nil )
                event.target.isFocus = false
            end
        end
        return true
    end

function inBounds( event )
    local bounds = event.target.contentBounds
    if event.x > bounds.xMin and event.x < bounds.xMax and event.y > bounds.yMin and event.y  < bounds.yMax then
        return true
    else
        return false
    end
end 

此代码还将查找对象的边界。例如,如果用户触摸屏幕,然后将他/她的手指移到对象之外,则对象将不再被聚焦。加油^^

于 2013-05-28T09:34:16.113 回答