isCollided method

int isCollided(
  1. DFShape shape
)

检查碰撞和遮挡 遮挡1 碰撞2 没有0

Implementation

int isCollided(DFShape shape) {
  bool isBlock = false;
  bool isAlpha = false;

  if (blockLayer != null && alphaLayer != null) {
    List<DFPosition> points = [];
    if (shape is DFRect) {
      points.add(DFPosition(shape.left, shape.top));
      points.add(DFPosition(shape.right, shape.top));
      points.add(DFPosition(shape.right, shape.bottom));
      points.add(DFPosition(shape.left, shape.bottom));
    } else if (shape is DFCircle) {
      points.add(DFPosition(shape.center.x - shape.radius, shape.center.y - shape.radius));
      points.add(DFPosition(shape.center.x + shape.radius, shape.center.y - shape.radius));
      points.add(DFPosition(shape.center.x - shape.radius, shape.center.y + shape.radius));
      points.add(DFPosition(shape.center.x + shape.radius, shape.center.y + shape.radius));
    }

    int columnCount = tileMap!.width!;
    double scaledTiledWidth = this.tileMap!.tileWidth! * this.scale;
    double scaledTiledHeight = this.tileMap!.tileHeight! * this.scale;

    /// 获取形状的4个点进行判断碰撞,比遍历性能会高很多
    for (int i = 0; i < points.length; i++) {
      int row = (points[i].y / scaledTiledHeight).ceil() - 1;
      int column = (points[i].x / scaledTiledWidth).ceil() - 1;

      /// print("row:" + row.toString() + ",column:" + column.toString());
      int index = row * columnCount + column;

      /// print("index:" + index.toString());
      if (blockLayer!.data![index] != 0) {
        isBlock = true;
        break;
      } else if (alphaLayer!.data![index] != 0) {
        isAlpha = true;
      }
    }
  }
  if (isBlock) {
    return 2;
  } else if (isAlpha) {
    return 1;
  }
  return 0;
}