代码之家  ›  专栏  ›  技术社区  ›  QuestionEverything

如何在corona sdk中锚定矩形内的对象?

  •  0
  • QuestionEverything  · 技术社区  · 7 年前

    我试图在一个大矩形内添加一个小矩形,如下图所示,但似乎没有任何效果。我想使用锚,但我不知道如何继续。我试着把小矩形放在大矩形的右上角。任何建议都会非常有用!

    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)
    

    我正在努力实现的目标: enter image description here

    1 回复  |  直到 7 年前
        1
  •  1
  •   ldurniat    7 年前

    它可以通过多种方式实现。最简单的方法是将锚点更改为 (1, 0) . 它要求两个对象具有相同的 x y 坐标:

    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 )
    

    更通用的方法使用 bounds 显示对象的属性:

    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