2

我正在尝试为 HTML5 画布游戏创建一种存储和加载地图的方法。为此,我必须创建由变量引用的对象(函数)的新实例。这是我的代码。

    function Map(w, h) {
        if (typeof w == "undefined")
            this.width = 640;
        else
            this.width = w;

        if (typeof h == "undefined")
            this.height = 480;
        else
            this.height = h;

        this.obj = new Array();
        this.x = new Array();
        this.y = new Array();
        this.backgroundColor = "#C0C0C0";
    }

    Map.prototype.addObject = function(cl, xx, yy) {
        this.obj.push(cl);
        this.x.push(xx);
        this.y.push(yy);
    }

    function newInstance(o, x, y) {
        this.tmp = new o(); //This is what doesn't work.
        tmp.x = x;
        tmp.y = y;
        objects.push(tmp);
        tmp.create();
    }

    Map.prototype.load = function() {
        for (var i = 0; i < this.obj.length; i++) {
            newInstance(this.obj[i], this.x[i], this.y[i]);
        }
    }

我希望它被这样使用:

    //When I create the map.
    var mMain = new Map();

    //This cannot be new Player() and new Block() because I don't want to load the map yet. I'm just creating the map.
    mMain.addObject(Player, 320, 240);
    mMain.addObject(Block, 0, 256);
    mMain.addObject(Block, 32, 256);
    //etc...

    //When I load the map.
    mMain.load();

只是 Player 和 Block 对象如何工作的一个示例。

    function Player() {
        this.x = 0;
        this.y = 0;
        //Other variables irrelevant to this problem.
    }
    //Block object code
4

1 回答 1

0

我解决了这个问题。我忘记在发布之前检查我的所有代码,所以我提供了虚假信息。而不是“function Player()”,我有“var Player = ObjectResource;” 因为我希望它扩展 ObjectResource 函数。我只需要将其更改为我发布的内容。

于 2012-06-24T19:35:53.347 回答