【问题标题】:Why am I unable to access the methods of an object via is ObjectContainer为什么我无法通过 is ObjectContainer 访问对象的方法
【发布时间】:2018-05-15 02:27:23
【问题描述】:

首先,我不是以英语为母语的人,但是,我仍然会尽我最大的努力让人们理解并尽可能清晰。

所以,在我的编程课上,我需要使用 animate cc(flash)制作一个基于 Tile 的游戏(例如 zelda)。在地图上,我想用随着音乐节奏变化的瓷砖制作舞池。这些图块是带有两帧的影片剪辑,一白一红。

这就是图块的生成方式:

private function createGrid(): void {

        grid = new MovieClip();
        addChild(grid);
        for (var r: int = 0; r < nbRow; r++) {
            for (var c: int = 0; c < nbCol; c++) {
                var t: Tiles = new Tiles();
                t.x = t.width * c;
                t.y = t.height * r;
                grid.addChild(t);
            }
        }

        grid.x = 15; //center the grid on x
        grid.y = 35; //center the grid on y
}

这是瓷砖类:

package {
import flash.display.MovieClip;
import flash.events.*;

public class Tiles extends MovieClip {
    private var rand:int;

    public function Tiles() {
        // constructor code
        getTiles();
    }
    public function getTiles():void {
        random();
        setColor();
    }
    private function random() : void{
        rand = Math.floor(Math.random()*100)+1;
    }

    private function setColor() : void{
        if(rand<=30){
            gotoAndStop(8); //red frame
        }else{
            gotoAndStop(7); //white frame
        }
    }
}

}

createGrid() 将地图放在舞台上后立即放置图块,并将每个图块存储在 MovieClip grid 中。现在,我希望瓷砖在流媒体音乐的节拍上在红色和白色之间随机变化(并保持 30% 红色瓷砖和 70% 白色瓷砖的比例)

var s: Sound = new Sound();
var sc: SoundChannel;

s.load(new URLRequest("GameSong_mixdown.mp3"));
sc = s.play(0, 1000);

我知道我需要我的声道的 leftpeek 属性来实现这一点,但现在,我使用触发此功能的按钮进行测试:

private function setTiles(e: Event): void {
        // loop through all child element of a movieclip
        for (var i: int = 0; i < grid.numChildren; i++) {
            grid.getChildAt(i).getTiles();          
        }
    }

现在,问题是:我无法访问我的 Tiles 方法。我在网格上进行了跟踪,getChildAt(i),并在控制台中看到了我的瓷砖的所有实例。所以,我确定我的图块的每个实例都存储在网格中。但是,我不知道为什么,grid.getChildAt(i).getTiles();不起作用(以及 Tiles 中的所有其他方法)。错误消息是:通过静态类型 flash.display:DisplayObject 的引用调用可能未定义的方法 getTiles

有人知道我做错了吗?

ps:我将我所有的类名、变量名等从法语翻译成 英文让代码更清晰。

【问题讨论】:

    标签: actionscript-3 object random methods actionscript


    【解决方案1】:

    您的错误是 getChildAt(...) 方法的返回类型为 DisplayObject 既不是动态的(不会让您访问随机属性)也不是DisplayObject.getTiles() 方法。

    你只需要告诉程序这个对象实际上是 Tiles 类:

    private function setTiles(e:Event):void
    {
        // loop through all child element of a movieclip
        for (var i: int = 0; i < grid.numChildren; i++)
        {
            // Cast display objects to Tiles class.
            var aTiles:Tiles = grid.getChildAt(i) as Tiles;
    
            // Call the method.
            aTiles.getTiles();          
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-19
      • 2015-12-13
      • 1970-01-01
      相关资源
      最近更新 更多