纯小白在学习制作2D游戏中遇到的问题

贴代码,或者放git上让大家看看,初学者最常见的是拼错了,写漏了

import { _decorator, CCInteger, Component, instantiate, Node, Prefab} from ‘cc’;
const { ccclass, property } = _decorator;

enum BlockType{
BT_NONE,
BT_STONE,
};

@ccclass(‘GameManager’)
export class GameManager extends Component {

@property({type: Prefab})
public boxPrefab: Prefab|null = null;
@property({type: CCInteger})
public roadLength: number = 50;
private _road: BlockType[] = [];

start() {
     
    this.generateRoad();        
}

generateRoad() {

  this.node.removeAllChildren();

  this._road = [];
  // startPos
  this._road.push(BlockType.BT_STONE);

  for (let i = 1; i < this.roadLength; i++) {
      if (this._road[i - 1] === BlockType.BT_NONE) {
          this._road.push(BlockType.BT_STONE);
      } else {
          this._road.push(Math.floor(Math.random() * 2));
      }
  }

  for (let j = 0; j < this._road.length; j++) {
      let block: Node | null = this.spawnBlockByType(this._road[j]);
      if (block) {
          this.node.addChild(block);
          block.setPosition(j * BLOCK_SIZE, 0, 0);
      }
  }

}

spawnBlockByType(type: BlockType) {
if (!this.boxPrefab) {
return null;
}

  let block: Node|null = null;
  switch(type) {
      case BlockType.BT_STONE:
          block = instantiate(this.boxPrefab);
          break;
  }

  return block;

}
}

代码贴上了,辛苦大佬帮忙看看

image
你是不是没有把预制体拖到这里

拖进去了 :face_with_thermometer:

image

可以学习一下断点调试,这样找问题会快很多,很多问题不太好一眼看出是哪里的问题,用断点看你代码是怎么走的,就一目了然了

嗯?GameManager我用的你的 PlayerController我用的官方的 是可以生成地图的
image

要不PlayerController也贴出来 或者直接分享整个项目更容易看到啥问题

不对 根本不关PlayerController的事情,那可能是预制体的问题,有可能是生成了没有显示。
看看你的预制体什么样 Node的Layer属性是什么

可能没有走到创建节点,也可能坐标错了偏到屏幕外了,可以多打一些日志看看。

可以装一下这个网页调试工具,运行后可以实时查看、修改节点树,实时更新节点属性,方便调试。https://github.com/potato47/ccc-devtools

1赞

image

image 然后检查一下摄像机有没有渲染UI_2D 如果没有勾上。勾上还不显示的话。用编辑器预览运行一下image
image 看看有没有生成这一堆box,看看box的位置,可见性还有父节点的位置对不对(感觉父节点的位置不对概率很大)。如果还是排查不出来就放git上吧,我来帮你看看。