Corona SDK - 如何检测非物理体上的碰撞?

时间:2012-02-02 22:44:00

标签: iphone collision corona

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

在纸牌中,牌是可拖动的物体。当它们被释放到另一堆牌的顶部(碰撞)时,它们会“粘住”到那个牌组。目标热点(卡片堆栈)并不总是提前知道 - 它们是动态的。

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

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

在移动卡片的功能中,使用

添加与底层卡片堆交叉的检查
CGRectIntersect (card, cardStack) 

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

我也刚刚开始使用电晕,在您的问题主题上找到了可能有用的主题:

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

相关问题