hitTestObject with dynamically add movies

核能气质少年 提交于 2019-12-13 07:24:32

问题


I have code that adds a movie clip to the stage. The problem is, after it is added I want to add a hitTestObject on that object instance however I keep getting this error:

TypeError: Error #1034: Type Coercion failed: cannot convert "ast_0" to flash.display.DisplayObject.  at

spaceranger_fla::MainTimeline/addAstroid() at flash.utils::Timer/_timerDispatch() at flash.utils::Timer/tick()

Here is my code:

// Add astoid
var astTimer:Timer = new Timer(5000);
astTimer.addEventListener(TimerEvent.TIMER, addAstroid);
var i:Number = 0;
function addAstroid (e:TimerEvent):void{
    var ast = new astroid();
    ast.name = "ast_"+i;
    ast.y = Math.random()*stage.stageHeight;
    ast.x = 565;
    addChild(ast);
    if(ship.hitTestObject(ast.name)){
        gotoAndStop("2");
    }
    i = i+1;
}

I understand that ast.name is a string and not a display object, so how do I convert it to a display object?

Thanks,

Pedro


回答1:


Your question derives from a fundamental misunderstanding of the code and how exactly it works. Please don't take offense to that comment, all programmers start out this way. Your asking how you can convert a string into a display object so you can reference the object. The real question should be, "how do I find another method of referencing a display object?" There is a method you can use which will grab the object by it's name, and return the object to you. [parent].getChildByName() will allow you to pass the [object].name if you must conduct your program this way.

However, you have another problem with this function. If you take my advice above, you will probably edit your code and you still will not see the results you are looking for, which would lead you to the bad conclusion that I'm wrong. This is not the case, let me explain. You are adding an object to the stage, and doing the hitTest() all in the same moment. Once the asteroid is added, it's essentially finished checking the hit test. Even if you had all your code correct, it would not return you the results you are looking for. You will need a separate function OUTSIDE of addAstroid() to handle your hit test.

In conclusion: Given the code you have provided, and the question you asked, I would simply suggest programming simpler concepts before you move on to a full fledged game (even a seemingly simple game like Asteroids). I would also suggest learning enough to make sense of errors. The voice of your system is the error itself, if you don't understand the errors, you won't understand what your system is telling you. These are merely suggestions, not commands.

This link should help explain display objects and the method you are using. ActionScript 3 - DisplayObject.hitTestObject()



来源:https://stackoverflow.com/questions/16384424/hittestobject-with-dynamically-add-movies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!