【问题标题】:Corona SDK - How to detect collision on a non-physics body?Corona SDK - 如何检测非物理物体上的碰撞?
【发布时间】:2012-02-02 22:44:00
【问题描述】:

我们使用的对象不一定需要利用物理引擎,但我们仍然需要检测碰撞。这是一个与我们正在尝试构建的示例类似的示例:

在纸牌中,卡片是可拖动的对象。当它们被释放到另一叠纸牌的顶部(碰撞)时,它们将“粘”在该牌组上。目标热点(卡片堆)并不总是提前知道的——它们是动态的。

在 Corona SDK 中解决这个问题的最佳方法是什么?

【问题讨论】:

    标签: iphone collision coronasdk


    【解决方案1】:

    如果你不想使用物理引擎,你可以编写一个触摸事件监听器来检查重叠的卡片。我假设一堆卡片或单张卡片没有区别。

    local cards={} --a list of display objects
    cards[1]=display.newRect(100,100,100,100)
    cards[2]=display.newRect(100,210,100,100)
    cards[3]=display.newRect(100,320,100,100)
    
    local tolerance=20 --20px radius
    local cardAtPointer=0  --the index of the card stuck to user hand
    
    local function onOverlap(self,event)
        if event.phase == "began" then
            cardAtPointer=self.index    --hold one card only    
        elseif event.phase == "moved" then
            if cardAtPointer > 0 and self.index == cardAtPointer then
                self.x,self.y = event.x,event.y     --drag card around
            end
        elseif event.phase == "ended" or event.phase == "cancelled" then
            local s=self
    
            for i=1,#cards do
                local t=cards[i]
                if s.index ~= t.index then  --dont compare to self
                    if math.pow(tolerance,2) >= math.pow(t.x-s.x,2)+math.pow(t.y-s.y,2) then
                        print(s.index.." overlap with "..t.index)
                        break   --compare only 2 overlapping cards, not 3,4,5...
                    end
                end
            end
            cardAtPointer=0     --not holding any cards
        end
    end
    
    for i=1,#cards do 
        cards[i].index=i
        cards[i].touch=onOverlap
        cards[i]:addEventListener("touch",cards[i])
    end
    

    【讨论】:

    • 到目前为止,这段代码运行良好。 “移动”阶段的 x/y 运动有点不稳定,但我想我可以从这里管理。这解决了非物理实体问题上的碰撞检测。谢谢!
    【解决方案2】:

    在移动你的卡片的函数中,添加一个检查与底层卡片堆栈的交叉使用

    CGRectIntersect (card, cardStack) 
    

    并触发一个事件。 (假设卡片是矩形的)。

    我也刚开始使用电晕,发现这个主题可能对您的问题有所帮助:

    http://developer.anscamobile.com/forum/2010/10/29/collision-detection-without-physics

    【讨论】:

    • CGRectIntersect 不是 Objective C 函数吗?但是,您的链接中似乎有很多有用的代码...我会试一试!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多