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

ActionScript3:如果您单击的对象是那种类型的对象,您如何比较

  •  0
  • matthy  · 技术社区  · 16 年前

    代码如下:

    var newBlok:Boolean;
    var blokIndex:int = 0;
    var blokje:blok;
    var huidigBlok:DisplayObject;
    var prullenBak:DisplayObject = getChildByName("groen_mc");
    
    stage.addEventListener(MouseEvent.MOUSE_DOWN,pickUp);
    stage.addEventListener(MouseEvent.MOUSE_UP,dropIt);
    
    function pickUp(event:MouseEvent):void
    {
        trace(event.currentTarget);
        trace(event.target);
        trace(event.target.name);
    
        if (event.target.name == "mc1_mc")
        {
            trace("hoi");
    
            blokje = new blok;  
            blokje.name = "blokje" + blokIndex;
            blokIndex++;
    
            addChild(blokje);
            blokje.startDrag(true);
    
        }
    
        if (event.target.type == blok)
        {
            trace("blok");
        }
    
        //blokjeVast = blokje;
    }
    
    function dropIt(event:MouseEvent):void
    {
        event.target.stopDrag();
    }
    

    即使我点击的对象给出:

    [object Stage]
    [object blok]
    blokje0
    

    为了线路。

    trace(event.currentTarget);
    trace(event.target);
    trace(event.target.name);
    

    有人知道如何检查它是否是“blok”类型的对象吗?

    1 回复  |  直到 16 年前
        1
  •  1
  •   Juan Pablo Califano    16 年前

    要检查对象是否属于特定类型,可以使用 is

    所以,你应该改变这个:

    if (event.target.type == blok)
    {
        trace("blok");
    }
    

    if(event.target is blok) 
    {
        trace("blok");
    }
    

    如果目标是blok类型,您应该可以看到跟踪。

    这里有一个警告。 ìs 告诉您某个对象是否属于某个类型。因为一个类可以扩展其他类并实现接口,所以您应该首先检查最派生的或最特定的类(如果您想区分Sprite和MovieClip)。

    var mc:MovieClip = new MovieClip();
    
    if(mc is MovieClip) {
        trace("is MovieClip");
    } else if(mc is Sprite) {
        trace("is Sprite");
    }
    
    // even if mc is a MovieClip, your code will never get in the else block
    if(mc is Sprite) {
        trace("is Sprite");
    } else if(mc is MovieClip) {
        trace("is MovieClip");
    }