如何检查鼠标是否在MovieClip上?

nic*_*cks 1 mouseover actionscript-3 movieclip

没有听众参与.问题是,我可以使用MOUSE_OVERMOUSE_OUT侦听器,但是如果将鼠标快速拖动到MovieClip上,则可能无法激活其中一个侦听器.我试了好几次.

L0L*_*NJ4 10

我从未遇到过mouseOver和mouseOut的问题.

但是你可以使用hitTestPoint:

function detectMouseOver(d:DisplayObject):Boolean
{
    var mousePoint:Point = d.localToGlobal(new Point(d.mouseX,d.mouseY));
    return d.hitTestPoint(mousePoint.x,mousePoint.y,true);
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用stage.mouseX和stage.mouseY(而不是localToGlobal),如果您确定该属性可用并从您调用的位置进行设置.

我没有测试过代码,但我认为它应该可行.

(编辑)

但是如果你想要绝对确定鼠标越过一个物体 - 即使你走得太快就要完全跳过它,你必须检查两帧鼠标点之间的点.

这将使它成为例如:

d.addEventListener(Event.ENTER_FRAME, checkMouseOver);

var lastPoint:Point;
const MAX_DIST:Number = 10;

function checkMouseOver(e:Event):void
{
    var isOver:Boolean = false;

    var d:DisplayObject = e.currentTarget as DisplayObject;
    var thisPoint:Point = d.localToGlobal(new Point(d.mouseX,d.mouseY))

    if (lastPoint)
    while (Point.distance(thisPoint,lastPoint) > MAX_DIST)
    {
        var diff:Point = thisPoint.subtract(lastPoint);
        diff.normalize(MAX_DIST);
        lastPoint = lastPoint.add(diff);

        if (d.hitTestPoint(lastPoint.x,lastPoint.y,true))
        {
            isOver = true;
            break;
        }
    }
    if (d.hitTestPoint(thisPoint.x,thisPoint.y,true))
    isOver = true;

    lastPoint = thisPoint;

    //do whatever you want with isOver here
}
Run Code Online (Sandbox Code Playgroud)

您可以记住,如果上次状态结束,并在isOver!= wasOver时调度自定义事件.如果你在while循环中执行此操作,则可以获得高度准确的鼠标过度检测.

但我敢打赌,使用shapeFlag = true的hitTestPoint相当CPU重,特别是如果在一帧中使用了很多.因此,在这种情况下,您可能希望将此MAX_DIST设置为尽可能高.