QuestionEverything
QuestionEverything

Reputation: 65

How to anchor object inside a rectangle in corona sdk?

I am trying to add a little rectangle inside of a big rectangle as seen in the images below but nothing seems to be working. I want to use anchors but I do not know how to proceed. I am trying to put the little rectangle in the top right corner of the bigger rectangle.Any advice would be extremely helpful!

local bigRectangle = display.newRect(200,200,320,400)
bigRectangle:setFillColor(0,0,1)
bigRectangle.x = _X
bigRectangle.y = _Y

local smallRectangle = display.newRect(200,200,20,20)
bigRectangle:setFillColor(255/255,255/255,0/255)

what I am trying to accomplish: enter image description here

Upvotes: 0

Views: 196

Answers (1)

ldurniat
ldurniat

Reputation: 1702

It can be accomplish in many ways. The simplest way is to change anchor point to (1, 0). It requires that both objects have the same x and y coords:

local bigRectangle = display.newRect( 200, 200, 320, 400 )
bigRectangle.anchorX, bigRectangle.anchorY = 1, 0
bigRectangle:setFillColor( 0, 0, 1 )

local smallRectangle = display.newRect( 200, 200, 20, 20 )
smallRectangle.anchorX, smallRectangle.anchorY = 1, 0
smallRectangle:setFillColor( 255 / 255, 255 / 255, 0 / 255 )

More universal method use bounds property of display objects:

local bigRectangle = display.newRect( 200, 200, 320, 400 )
    bigRectangle:setFillColor( 0, 0, 1 )
    bigRectangle.x = _X
    bigRectangle.y = _Y

    local smallRectangle = display.newRect( 200, 200, 20, 20 )
    smallRectangle:setFillColor( 255 / 255, 255 / 255, 0 / 255 )

    local bounds = bigRectangle.contentBounds
    smallRectangle.x = bounds.xMax - smallRectangle.width * smallRectangle.anchorX
    smallRectangle.y = bounds.yMin + smallRectangle.height * smallRectangle.anchorY 

Upvotes: 1

Related Questions