2013-02-11 43 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