使用Pixi.js优化提示的简单游戏

时间:2018-07-30 14:22:12

标签: javascript pixi.js game-development

我编写了一个小模拟程序,您可以在其中挖掘多维数据集,将多维数据集掉落,可以消耗一些多维数据集或使选择爆炸。

我开始玩这个小项目很有趣,我的目标是处理尽可能多的多维数据集(100k是一个好的开始)。

该项目很简单,有3种可能的动作:

  • 挖方(每次2k点击)
  • 使用多维数据集(每次单击50个)
  • 分解立方体(单击两个点以形成一个矩形)

当前,在我的计算机上,当我得到约2万个多维数据集时,性能开始下降。当选择大量的多维数据集爆炸时,性能也会大大降低。我不确定简化物理学的方法是最好的方法。

您能给我一些有关如何改进/优化它的提示吗?

这是完整的代码:(堆栈在SO代码段中无效,因此here is the codepen version

(() => {
  // Variables init
  let defaultState = {
    cubesPerDig : 2000,
    cubesIncome : 0,
    total : 0
  };
  let cubeSize = 2, dropSize = window.innerWidth, downSpeed = 5;
  let state,
      digButton, // Button to manually dig
      gameState, // An object containing the state of the game
      cubes, // Array containing all the spawned cubes
      heightIndex, // fake physics
      cubesPerX, // fake physics helper
      playScene; // The gamescene
  
  // App setup
  let app = new PIXI.Application();
  app.renderer.view.style.position = "absolute";
  app.renderer.view.style.display = "block";
  app.renderer.autoResize = true;
  document.body.appendChild(app.view);
  
  // Resize
  function resize() {
    app.renderer.resize(window.innerWidth, window.innerHeight);
  }
  window.onresize = resize;
  resize();
  
  // Hello ! we can talk in the chat.txt file
  
  // Issue : When there are more than ~10k cubes, performance start to drop
  // To test, click the "mine" button about 5-10 times
  
  // Main state
  function play(delta){
    // Animate the cubes according to their states
    let cube;
    for(let c in cubes){
      cube = cubes[c];
      switch(cube.state) {
        case STATE.LANDING:
          // fake physics
          if(!cube.landed){
            if (cube.y < heightIndex[cube.x]) {
              cube.y+= downSpeed;
            }else if (cube.y >= heightIndex[cube.x]) {
              cube.y = heightIndex[cube.x];
              cube.landed = 1;
              heightIndex[cube.x] -= cubeSize;
            }
          }
          break;
        case STATE.CONSUMING:
          if(cube.y > -cubeSize){
            cube.y -= cube.speed;
          }else{
            removeCube(c);
          }
          break;
        case STATE.EXPLODING:
          if(boundings(c)){
            continue;
          }
          cube.x += cube.eDirX;
          cube.y += cube.eDirY;
          break;
      }
    }
    updateUI();
  }
  
  // Game loop
  function gameLoop(delta){
    state(delta);
  }
  
  // Setup variables and gameState
  function setup(){
    state = play;
    digButton = document.getElementById('dig');
    digButton.addEventListener('click', mine);
    playScene = new PIXI.Container();
    gameState = defaultState;
    
    /* User inputs */
    // Mine
    document.getElementById('consume').addEventListener('click', () => {consumeCubes(50)});
    // Manual explode
    let explodeOrigin = null
    document.querySelector('canvas').addEventListener('click', e => {
      if(!explodeOrigin){
        explodeOrigin = {x: e.clientX, y: e.clientY};
      }else{
        explode(explodeOrigin, {x: e.clientX, y: e.clientY});
        explodeOrigin = null;
      }

    });
    window['explode'] = explode;

    heightIndex = {};
    cubesPerX = [];
    // Todo fill with gameState.total cubes
    cubes = [];
    app.ticker.add(delta => gameLoop(delta));
    app.stage.addChild(playScene);
  }
  
  /*
  * UI
  */
  function updateUI(){
    document.getElementById('total').innerHTML = cubes.length;
  }
  
  /*
  * Game logic
  */
  // Add cube when user clicks
  function mine(){
    for(let i = 0; i < gameState.cubesPerDig; i++){
      setTimeout(addCube, 5*i);
    }
  }
  
  // Consume a number of cubes
  function consumeCubes(nb){
      let candidates = _.sampleSize(cubes.filter(c => !c.eDirX), Math.min(nb, cubes.length));
      candidates = candidates.slice(0, nb);
      candidates.map(c => {
        dropCubes(c.x);
        c.state = STATE.CONSUMING;
      });
  }
  const STATE = {
    LANDING: 0,
    CONSUMING: 1,
    EXPLODING: 2
  }
  // Add a cube
  function addCube(){
    let c = new cube(cubeSize);
    let tres = dropSize / cubeSize / 2;
    c.x = window.innerWidth / 2 + (_.random(-tres, tres) * cubeSize);
    c.y = 0//-cubeSize;
    c.speed = _.random(5,8);
    cubes.push(c);
    c.landed = !1;
    c.state = STATE.LANDING;
    if(!cubesPerX[c.x]) cubesPerX[c.x] = [];
    if (!heightIndex[c.x]) heightIndex[c.x] = window.innerHeight - cubeSize;
    cubesPerX[c.x].push(c);
    playScene.addChild(c);
  }
  
  // Remove a cube
  function removeCube(c){
    let cube = cubes[c];
    playScene.removeChild(cube);
    cubes.splice(c,1);
  }
  
  // Delete the cube if offscreen
  function boundings(c){
    let cube = cubes[c];
    if(cube.x < 0 || cube.x + cubeSize > window.innerWidth || cube.y < 0 || cube.y > window.innerHeight)
    {
      removeCube(c);
      return true;
    }
  }
  
  // explode some cubes
  function explode(origin, dest){
    if(dest.x < origin.x){
      dest = [origin, origin = dest][0]; // swap
    }
    var candidates = cubes.filter(c => c.state != STATE.EXPLODING && c.x >= origin.x && c.x <= dest.x && c.y >= origin.y && c.y <= dest.y);
    if(!candidates.length)
      return;
    
    for(let i = origin.x; i <= dest.x; i++){
      dropCubes(i);
    }
    
    candidates.forEach(c => {
      c.explodingSpeed = _.random(5,6);
      c.eDirX = _.random(-1,1,1) * c.explodingSpeed * c.speed;
      c.eDirY = _.random(-1,1,1) * c.explodingSpeed * c.speed;
      c.state = STATE.EXPLODING;
    });
  }
  
  // Drop cubes
  function dropCubes(x){
    heightIndex[x] = window.innerHeight - cubeSize;
    if(cubesPerX[x] && cubesPerX[x].length)
      cubesPerX[x].forEach(c => {
        if(c.state == STATE.EXPLODING) return;
        c.landed = false; c.state = STATE.LANDING;
      });
  }
  
  /*
   * Graphic display
   */
  
  // Cube definition
  function cube(size){
    let graphic = new PIXI.Graphics();
    graphic.beginFill(Math.random() * 0xFFFFFF);
    graphic.drawRect(0, 0, size, size);
    graphic.endFill();
    return graphic;
  }
  
  // Init
  setup();
})()
/* styles */
/* called by your view template */

* {
  box-sizing: border-box;
}
body, html{
  margin: 0;
  padding: 0;
  color:white;
}

#ui{
  position: absolute;
  z-index: 2;
  top: 0;
  width: 0;
  left: 0;
  bottom: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/4.8.1/pixi.min.js"></script>
<script>PIXI.utils.skipHello();</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
<!-- Click two points to make cubes explode -->
<div id="ui">
    <button id="dig">
      Dig 2k cubes
    </button>
    <button id="consume">
      Consume 50 cubes
    </button>
    <p>
      Total : <span id="total"></span>
    </p>
  </div>

谢谢

1 个答案:

答案 0 :(得分:2)

使用Sprite总是比使用Graphics更快(至少直到出现v5!)

所以我将多维数据集创建功能更改为

function cube(size) {
    const sprite = new PIXI.Sprite(PIXI.Texture.WHITE);
    sprite.tint = Math.random() * 0xFFFFFF;
    sprite.width = sprite.height = size;
    return sprite;
}

那为我自己提高了fps