The Corona display object is set out

I have several drag and drop objects that can be moved around the screen. I want to set a border so that they cannot be pulled out of the screen. I cannot find what I am looking for for this.

+3


source to share


2 answers


There are several ways to do this.

You can set up some static physics bodies as walls (just off screen edges) and attach dynamic physics bodies to your dragged objects. You will need to set up custom collision filters if you don't want multiple dragged objects to collide with each other.

The easiest way (if your objects are not physics objects yet) is to place all of your dragged items into a table. Then, in a Runtime listener, constantly check the x and y positions of your objects. for example



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)

      

This loop assumes that the control point of your images is in the center, you will need to adjust it if it is not.

+5


source


I would also like to add for those who need their object to be more or less off-screen, you need to make the following code changes (And please keep in mind that Gooner toggles "> & lt" around the comment " I also renamed a few vars (minimumX / maximumX to tBandStartX / tBandEndX), so keep that in mind.

-- 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)

      



Thank you TheBestBigAl for helping me get where I needed to with this feature!

-Robbie

+1


source







All Articles