【问题标题】:typescript assign specific coordinate to x and y打字稿将特定坐标分配给 x 和 y
【发布时间】: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


    【解决方案1】:

    每次实例化一个新的Obstacles 对象时,都会循环遍历数组_obstX,将x 属性设置为数组中的第n 个值。所有Obstaclesx 值为400,因为for 循环的最后一次迭代将this.x 设置为数组中的最后一个值。

    我会将_obstX 数组移动到主文件,并将x 参数/属性添加到您的Obstacles 构造函数中。我不确定你现在的构造函数看起来如何,但可能是这样的:

    constructor(private assetManager: AssetManger, private x: number) {}
    

    然后调用构造函数:

    new objects.Obstacles(this.assetManager, _obstX.shift())
    

    这会将_obstX 中的第一个元素发送到构造函数,并从数组中删除该值。当您创建每个 Obstacles 对象时,它将具有数组中的下一个 x 值。

    【讨论】:

    • 你是对的,它只取循环的最后一个值,我按照你的建议,然后在构造函数中,我设置了this.x = x,现在它可以正常工作了。
    猜你喜欢
    • 2021-11-21
    • 2021-03-02
    • 2021-12-06
    • 2013-06-25
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    相关资源
    最近更新 更多