You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为2D无限跑酷游戏新增type3块实现随机场景生成

代码调整方案

1. 修改addPlatform方法的类型分支判断

你需要把原来的二元分支判断扩展为三元,匹配type=3的情况加载block3资源,修改后的代码如下:

addPlatform(width, x, y, type) {
  let platform;
  if(type == 1){
    platform = this.add.tileSprite(x+width/2, y, width, 32, "block1");
  } else if(type == 2) {
    platform = this.add.tileSprite(x+width/2, y, width, 32, "block2");
  } else if(type == 3) {
    platform = this.add.tileSprite(x+width/2, y, width, 32, "block3");
  }
  // 原有物理属性配置逻辑保留
  this.physics.add.existing(platform);
  platform.body.setVelocityX(-200);
  platform.body.setImmovable(true);
  this.platformGroup.add(platform);
}

如果想代码更简洁可维护,也可以用资源映射对象替代多分支if,后续新增平台类型只需要更新映射关系即可:

addPlatform(width, x, y, type) {
  const blockResMap = {
    1: "block1",
    2: "block2",
    3: "block3"
  }
  const platform = this.add.tileSprite(x+width/2, y, width, 32, blockResMap[type]);
  this.physics.add.existing(platform);
  platform.body.setVelocityX(-200);
  platform.body.setImmovable(true);
  this.platformGroup.add(platform);
}

注意:操作前请确保你已经在preload阶段提前加载了block3的纹理资源,否则会出现资源缺失报错。

2. 新增三类平台随机生成逻辑

在调用addPlatform生成平台的位置,添加随机生成1~3整数的逻辑即可实现随机出块:

// 示例:生成随机type的调用代码
const randomType = Phaser.Math.Between(1, 3); // 用Phaser自带的随机方法生成1-3的整数
// 传入参数调用addPlatform,width、x、y用你原有计算逻辑的数值即可
this.addPlatform(platformWidth, spawnX, spawnY, randomType);

内容的提问来源于stack exchange,提问作者SeTx69

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 09:42:01