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


 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值