微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

被复制的类的相同实例

如何解决被复制的类的相同实例

我正在尝试创建一种方法来为游戏打印出基于平铺的正方形网格。这是一个 2D RPG 风格的游戏,所以我想为不同的图块(碰撞、不同的艺术等)设置不同的属性。目前,我有一个用于瓷砖的基类和一个名为 tileObjectDirectory 的数组,用于给我提供属性的瓷砖,并且基本上想要在网格上复制和粘贴。我的问题是我试图将 x 和 y 值分配到应该打印的位置,但似乎我推入的每种类型的瓷砖都分配了相同的值。例如,所有路径图块都获得相同的 X 值。这是我如何初始化每个图块的问题吗?

//blank tile class
class tile {

constructor(name,ID,x,y) {
this.name = name;
this.ID = ID;   
this.x = x;
this.y = y;
}

}

//defining tiles
let Path = new tile("path","p",0);
let Test = new tile("test","t",0);


//this array store all the current types of tiles in the game
//let tileObjectDirectory = [Path,Test];
let tileObjectDirectory = [new tile("path",0),new tile("test",0)];

function tileSelector(tileID) {
let tileObject;

switch (tileID) {
    case "p":
        tileObject = tileObjectDirectory[0];
        break;
    case "t":
        tileObject = tileObjectDirectory[1];
        break;
    }

return tileObject;
}

//takes in an array of tile id's chars and outputs an array of the corresponding tile objects
function initializeTileObjects(tileIDArray) {
let tileObjects = [];
let tileX = 0;
let tileY = 0;

//go through array of ids and put the correct objects in the new array
for (let i = 0; i < tileIDArray.length; i++) {
//tileObjects[i] = tileSelector(tileIDArray[i]);
tileObjects.push(tileSelector(tileIDArray[i]));

console.log(`initializing i = ${i}:`,tileObjects[i]);
}
//console.log("before:",tileObjects);

//assigning the correct coordinates to the tiles
for (let i = 0; i < tileObjects.length; i++) {
tileObjects[i].x = tileX;
//tileObject[i].y = tileY;
tileX += 1;
console.log(`tileX = ${tileX},i = ${i}`);
}

console.log(tileObjects);

return tileObjects;
}

//main function for creating a map
function createMap(tileIDArray) {

tileObjectArray = initializeTileObjects(tileIDArray);

console.log(tileObjectArray);
}

我正在调用 createMap();像这样,

createMap(["p","t"]);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。