Dragging after positioning

How can I center an object inside another but still be able to drag it in the parent container containing both objects. In the code below the red circle appears to be underneath the tile and thus can't be dragged:

function fiveFrame() {
    let fivetile = new Tile(new Rectangle(110, 110, white, black), 5, 1)
        .sca(0.5);

    let targetItem = fivetile.items[rand(0, 4)];

    new Circle(40, red)
        .addTo(targetItem)
        .center()
        .top()
        .drag(); 

    framesArray.push(fivetile);
}
new Circle(40, red)
    .center(targetItem)
    //.top()
    .drag();

@Netanela points out that you can just use center(container) but there are a couple other issues that are causing the problem:

The circle object is being added to a Rectangle. The ZIM shapes are containers so you can do that, but they have their mouseChildren set to false by default. That is so when you drag a rectangle, it does not drag the shape inside the rectangle and leave the rectangle object (the container) stationary. So you can use:

targetItem.mouseChildren = true;

The other issue is that the top() is on the circle - that will make the circle go to the top of its container which is the rectangle. But the rectangle will not be at the top of the tile - it will be in the order that the tile is made - so if it is the last rectangle, it will be on the top of all of them but if it is the first rectangle, it will be under the rest. Depending on what else you are doing, you could just add:

targetItem.top();

Or you may need to do that in a mousedown event on the circle if you are adding other draggable items in other rectangles.

circle.on("mousedown", ()=>{circle.parent.top()});

Thank you very much @Netanela and @Abstract !

1 Like