2013-02-11 65 views
3

我有多个可拖动的对象,可以在屏幕上移动。我想设置一个边界,以便它们不能被拖出屏幕。我无法真正找到我想要做的事情。电晕停止对象被拖出屏幕

回答

5

有几种方法可以做到这一点。

您可以将某些静态物理体设置为墙(仅位于屏幕边缘之外),并将动态物理体附加到可拖动对象。如果您不希望多个可拖动对象相互碰撞,则需要设置自定义碰撞过滤器。

最简单的方法(假设您的对象不是物理对象)是将所有可拖动项目放入表格中。然后在运行时侦听器中,不断检查对象的x和y位置。例如

object1 = display.newimage..... 

local myObjects = {object1, object2, object3} 

local minimumX = 0 
local maximumX = display.contentWidth 
local minimumY = 0 
local maximumY = display.contentHeight 

local function Update() 

    for i = 1, #myObjects do 

     --check if the left edge of the image has passed the left side of the screen 
     if myObjects[i].x - (myObjects[i].width * 0.5) < minimumX then 
      myObjects[i].x = minimumX 

     --check if the right edge of the image has passed the right side of the screen 
     elseif myObjects[i].y + (myObjects[i].width * 0.5) > maximumX then 
      myObjects[i].x = maximumX 

     --check if the top edge of the image has passed the top of the screen 
     elseif myObjects[i].y - (myObjects[i].height * 0.5) < minimumY then 
      myObjects[i].y = minimumY 

     --check if the bottom edge of the image has passed the bottom of the screen 
     elseif myObjects[i].x + (myObjects[i].height * 0.5) > maximumY then 
      myObjects[i].y = maximumY 
     end 

    end 
end 

Runtime:addEventListener("enterFrame", Update) 

该循环假定图像的参考点位于中心,如果不是,则需要对其进行调整。

+0

谢谢你帮助我解决这个问题。小编辑,最大X和最大Y的符号需要从< to >更改,否则它总是<比maximumX或MaximumY – Gooner 2013-02-11 16:05:48

+0

我补充说,这是检查对象位置的最简单方法,但可能并不总是特别有效。如果需要,您也可以调整它来做出非常原始的碰撞检测。只需将minimumX,minimumY等改为另一个对象的左/右/上/下边缘(虽然这非常原始,并且不考虑诸如旋转之类的事情)。 – TheBestBigAl 2013-02-11 18:58:23

+0

我正在寻找这样简单的东西,我没有添加任何物理,我真的只是想确保我的瓷砖不会失去屏幕 – Gooner 2013-02-12 09:39:04

1

我也想为那些需要他们的对象的人添加更多或更多的屏幕外,您需要对代码进行以下调整(请记住Gooner切换“> <”围绕评论)我也将一些变量(minimumX/maximumX重命名为tBandStartX/tBandEndX)记住。

-- Create boundry for tBand 

local tBandStartX = 529 
local tBandEndX = -204 

    local function tBandBoundry() 
      --check if the left edge of the image has passed the left side of the screen 
      if tBand.x > tBandStartX then 
       tBand.x = tBandStartX 

      --check if the right edge of the image has passed the right side of the screen 
      elseif tBand.x < tBandEndX then 
       tBand.x = tBandEndX 
      end 
    end 

    Runtime:addEventListener("enterFrame", tBandBoundry) 

谢谢TheBestBigAl,帮助我到达需要使用此功能的地方!

-Robbie