2012-02-02 101 views
1

我们使用的对象不一定需要利用物理引擎,但我们仍然需要检测碰撞。这里有一个类似的例子,我们正在尝试构建:Corona SDK - 如何检测非物理体上的碰撞?

在单人纸牌中,牌是可拖动的物体。当他们被释放在另一叠牌(碰撞)的顶部时,他们将“坚持”该牌组。目标热点(卡片堆栈)并不总是事先知道 - 它们是动态的。

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

回答

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 
+0

这段代码目前效果很好。 “移动”阶段的X/Y移动有点波动,但我认为我可以从这里管理。这解决了非物理机构问题上的碰撞检测问题。谢谢! – Alex 2012-02-03 16:24:58

1

在应该使卡的功能,采用

CGRectIntersect (card, cardStack) 

添加一个检查交叉口与基础卡堆和触发事件。 (假设卡片是矩形的)。

我也刚开始使用电晕,发现这个线程对你的问题的话题,可能会有所帮助:

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

+0

是不是CGRectIntersect一个Objective C函数?然而,它看起来像你的链接有很多有用的代码在里面......我会试试看! – Alex 2012-02-03 15:42:25