Как удалить ребенка с тем же именем, если в том же месте или столкновение? AS3 - PullRequest
1 голос
/ 27 марта 2020

Итак, в моем сценарии я дал пользователю возможность делать неограниченное количество определенного фрагмента ролика.

var square = new Square();
sqaure.x = mouseX;
sqaure.y = mouseY;
addChild(square);

Однако я хотел бы, чтобы скрипт удалил все дополнительные дочерние элементы, добавленные к тем же координатам X и Y. Мне нужно убедиться, что он удаляет лишнего потомка, даже если они щелкают и убирают курсор, а затем возвращаются в уже заполненное место. Либо в файле .class, либо в самом основном скрипте.

Есть идеи? Спасибо

Ответы [ 2 ]

1 голос
/ 27 марта 2020

В момент щелчка вы можете получить список всех вещей под курсором мыши с помощью метода getObjectsUnderPoint (...) и удалить любое их подмножество в соответствии с критериями вашего вкуса.

// Stage, because if user clicks the current container
// into the empty area, the click won't register.
stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);

function onDown(e:MouseEvent):void
{
    var aPoint:Point = new Point;

    // Set it to the mouse coordinates.
    aPoint.x = mouseX;
    aPoint.y = mouseY;

    // Convert it to Stage coordinates.
    aPoint = localToGlobal(aPoint);

    // The returned list will contain only descendants
    // of the current DisplayObjectContainer.
    var aList:Array = getObjectsUnderPoint(aPoint);

    // Iterate through the results.
    for each (var aChild:DiaplayObject in aList)
    {
        // Now, filter the results to match certain criteria.

        // Don't bother with the grandchildren.
        if (aChild.parent != this) continue;

        // Ignore things if they are not of the right class.
        if (!(aChild is Square)) continue;

        // ...etc.

        // Remove those ones that have passed all the checks.
        removeChild(aChild);
    }

    // Add the new one here.

    var aSq:Square = new Square;

    aSq.x = mouseX;
    aSq.y = mouseY;

    addChild(aSq);
}
0 голосов
/ 02 апреля 2020

Одна вещь, которую сказал Органис, «addEventListener» - это то, на что вы можете взглянуть, используя поисковые термины «as3 event listener api». при поиске «api» будут приведены примеры кода и свойств Adobe c.

Вы можете попробовать поместить небольшие текстовые поля ввода и кнопку с прослушивателем событий, чтобы установить значения x и y для значений. из входных текстовых полей

Другое дело, я всегда делал лучше всего с массивами для хранения каждого элемента, который вы добавляете на сцену.

//global variables
    var nameSprite:Sprite;
    var name2Array:Array = new Array();
    var id:Number = 0;

//initial function
    nameSprite = new Sprite();
    addChild(nameSprite);
    name2Array = new Array();//seems redundant but has been what I've had to do to make it work

//other function to add items to the array
    var sqaure:objectName = new objectName();
    sqaure.x = mouseX;
    sqaure.y = mouseY;
    square.id = id;//I like to add an id to be able to better sort things
    nameSprite.addChild(sqaure);
    name2Array.push(sqaure);
    id++;

//function to remove items
    IndexPH = j;//j would be the index in the for loop to identify the entry to be removed
    nameSprite.removeChild(name2Array[IndexPH]);//removes from stage
    name2Array.splice(IndexPH,1);//removes from array

//function to sort the array after an item has been removed
    name2Array.sortOn(["id"], Array.NUMERIC);

Так что это куча вещи, с которыми можно возиться, если вам нужны идеи. Я склонен искать и искать, а затем найти немного кода для включения в мои проекты, при этом необязательно использовать каждую часть конкретного c примера кода.

...