【发布时间】:2018-08-23 19:19:00
【问题描述】:
我正在尝试用单个对象映射我的障碍。
我使用 random 将其随机散布在地图上,现在我想用一个数字数组对 X 和 Y 坐标进行硬编码,但 typescript 只使用循环的最后一个值作为 X 坐标。如何为每个障碍物分配特定编号?
随机生成
module objects {
export class Obstacles extends objects.GameObject {
public Start():void {
this.x = Math.floor(Math.random() * (640) - this.width) + this.halfWidth;
this.y = Math.floor(Math.random() * (480) - this.width) + this.halfWidth;
console.log("x " + this.x);
console.log("y " + this.y);
}
}
用数组指定 x 值
private _obstX: number [] = [200, 250, 300, 350, 400];
public Start():void {
for (let count = 0; count < this._obstX.length; count++) {
this.x = this._obstX[count];
}
this.y = Math.floor(Math.random() * (480) - this.width) + this.halfWidth;
console.log("x " + this.x);
console.log("y " + this.y);
}
只分配一个x值,忽略数组中的另一个x值
主文件中的代码
private _obstPlanes: objects.Obstacles[];
private _obstNum: number;
public Start(): void {
this._obstPlanes = new Array<objects.Obstacles>();
this._obstNum = 5;
for (let count = 0; count < this._obstNum; count++) {
this._obstPlanes[count] = new objects.Obstacles(this.assetManager);
}
}
public Main(): void {
this._obstPlanes.forEach(obstPlane => {
this.addChild(obstPlane);
});
}
【问题讨论】:
标签: arrays loops typescript