Question

I would like to expand my rect in width increasing by 1 and want it to stop when it reaches the screen width. However, It stops increasing in the middle of the screen in my code. Can you tell me please what I am missing?

W=display.contentWidth
H=display.contentHeight

local rect = display.newRect(0,0,0,100)
rect:setFillColor(0,255,0)

local function expand()
  rect.width= rect.width+1
  print(rect.width)
  if rect.width==W then
    Runtime: removeEventListener("enterFrame", expand)
  end
 end

Runtime: addEventListener("enterFrame", expand)
Was it helpful?

Solution

Not tested but this should work.

    W=display.contentWidth
    H=display.contentHeight

    local rect = display.newRect(0,0,0,100)
   rect:setFillColor(0,255,0)

   local function expand()
      rect.width= rect.width+1
      rect.x=0
      print(rect.width)
      if rect.width==W then
           Runtime :removeEventListener("enterFrame", expand)
      end
      end

    Runtime: addEventListener("enterFrame", expand)

All views in corona has topleft reference point as default, meaning that if you position them at (0,0,0,100) they will start at the top left corner with a height of 100pixels. The x value of the view(rect in this case) will be at its' left side.

Increasing the width of this rectangle will not change the position of the rectangle. Just make it wider. Therefore half of the increase in width is found beyond the screen, to the left in this case.

OTHER TIPS

you can find out what is happening in your code by putting rect.x=W/2 at the begging of your code as:

W=display.contentWidth
H=display.contentHeight

local rect = display.newRect(0,0,0,100)
rect:setFillColor(0,255,0)
rect.x = W/2          -- just put this in your code and see what actually happening

local function expand()
    rect.width= rect.width+1
    print(rect.width)
    if rect.width==W then
      Runtime :removeEventListener("enterFrame", expand)
    end
end
Runtime: addEventListener("enterFrame", expand) 

Now, you can solve this by the following code(I have used a variable named: incrementVal just for your convenience, for understanding the relation about rect size and position in your code):

W=display.contentWidth
H=display.contentHeight

local rect = display.newRect(0,0,0,100)
rect:setFillColor(0,255,0)

local incrementVal = 1
local function expand()
  rect.width= rect.width+incrementVal
  rect.x = rect.x + (incrementVal/2)  -- additional line, added for proper working
  if rect.width==W then
    Runtime :removeEventListener("enterFrame", expand)
  end
end
Runtime: addEventListener("enterFrame", expand)

Keep coding.............. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top