Starling Touch事件会引发意外错误

时间:2014-04-10 11:51:32

标签: actionscript-3 events touch starling-framework

如果其他人遇到同样的问题,我会在我的一些项目中遇到这个问题,但从未费心找到它。

为touchevents添加侦听器时,每件事都可以正常工作:

btn.addEventListener(TouchEvent.TOUCH,function(e:TouchEvent){
            var t:Touch = e.getTouch(stage);

            if(t.phase == TouchPhase.ENDED)
            {

                    resetBall();

            }
        });

但有时如果我的鼠标悬停在该对象上,我的项目会停止,并抛出以下错误。

TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at Function/Game.as$0:anonymous()[...src\Game.as:45]
    at starling.events::EventDispatcher/invokeEvent()[/Users/redge/Dropbox/Development/starling/starling/src/starling/events/EventDispatcher.as:141]
    at starling.events::TouchEvent/dispatch()[/Users/redge/Dropbox/Development/starling/starling/src/starling/events/TouchEvent.as:174]
    at starling.events::TouchProcessor/processTouches()[/Users/redge/Dropbox/Development/starling/starling/src/starling/events/TouchProcessor.as:186]
    at starling.events::TouchProcessor/advanceTime()[/Users/redge/Dropbox/Development/starling/starling/src/starling/events/TouchProcessor.as:135]
    at starling.core::Starling/advanceTime()[/Users/redge/Dropbox/Development/starling/starling/src/starling/core/Starling.as:379]
    at starling.core::Starling/nextFrame()[/Users/redge/Dropbox/Development/starling/starling/src/starling/core/Starling.as:369]
    at starling.core::Starling/onEnterFrame()[/Users/redge/Dropbox/Development/starling/starling/src/starling/core/Starling.as:568]

1 个答案:

答案 0 :(得分:0)

标准是在检查getTouch()属性之前检查从null返回的触摸对象是否为phase

var touch:Touch = e.getTouch( stage );
if ( touch ) {
    if( touch.phase == TouchPhase.ENDED ) {
       resetBall();
    }
}

来自八哥维基:

private function onTouch(event:TouchEvent):void
{
    var touch:Touch = event.getTouch(this, TouchPhase.BEGAN);
    if (touch)
    {
        var localPos:Point = touch.getLocation(this);
        trace("Touched object at position: " + localPos);
    }
}

http://wiki.starling-framework.org/manual/touch_events