cocos2d 触摸事件中 触摸点在目标范围内 怎么判断触摸到了目标

触摸事件中 判断触摸点在目标范围内 -- 需要保证在同一坐标系

1.保证在父节点的坐标系

    local function onTouchBegan(touch,event)
        local location = touch:getLocation() --返回openGL中的坐标
            --将touch点的坐标转为要判断矩形的父节点坐标系;target是要chum
        local pos = target:getParent():convertToNodeSpace(location)   --target是要触摸的目标
        local rect = target:getBoundingBox() --获取到的是相对父节点坐标系的rect

        --cc.rectContainsPoint      3.10版本API  containsPoint()无效
        if cc.rectContainsPoint(rect,pos) then
            print("contains me....")
        else
            print("false....")
        end
    end

    local listener  = cc.EventListenerTouchOneByOne:create()
          listener:registerScriptHandler(onTouchBegan, cc.Handler.EVENT_TOUCH_BEGAN)
    local eventDispatcher = self:getEventDispatcher()
          eventDispatcher:addEventListenerWithSceneGraphPriority(listener,self)
end

2.在自己坐标系

    local function onTouchBegan(touch,event)
        local location = touch:getLocation() --返回openGL中的坐标
            --将touch点的坐标转为要判断矩形的自己点坐标系;target是要chum
        local pos = target:convertToNodeSpace(location)   --target是要触摸的目标
        local r = target:getBoundingBox() --获取到的是相对父节点坐标系的rect
        local rect = cc.rect(0,0,r.width,r.height) --转换为自己坐标系中的rect
        --cc.rectContainsPoint; 3.10版本API  containsPoint()无效
        if cc.rectContainsPoint(rect,pos) then
            print("contains me....")
        else
            print("false....")
        end
    end

    local listener  = cc.EventListenerTouchOneByOne:create()
          listener:registerScriptHandler(onTouchBegan, cc.Handler.EVENT_TOUCH_BEGAN)
    local eventDispatcher = self:getEventDispatcher()
          eventDispatcher:addEventListenerWithSceneGraphPriority(listener,self)
end

3,在世界坐标系中 (转换步骤多)

local function onTouchBegan(touch,event)
        local pos = touch:getLocation()
       
        local rect = m2:getBoundingBox() --获取到的是相对父节点坐标系的rect
        local tmpPos = cc.p(rect.x,rect.y)
        local tmpPos2 = m2:getParent():convertToWorldSpace(tmpPos) --转换到世界坐标系下
        local r = cc.rect(tmpPos2.x,tmpPos2.y,rect.width,rect.height)
      
        if cc.rectContainsPoint(r,pos) then
            print("contains me....")
        else
            print("false....")
        end
    end

    local listener  = cc.EventListenerTouchOneByOne:create()
          listener:registerScriptHandler(onTouchBegan, cc.Handler.EVENT_TOUCH_BEGAN)
    local eventDispatcher = self:getEventDispatcher()
          eventDispatcher:addEventListenerWithSceneGraphPriority(listener,self)
end


 
  


你可能感兴趣的:(cocos2d-x)