HTML5 Game (Canvas) - UI Techniques?

前端 未结 3 1818
遥遥无期
遥遥无期 2020-12-31 14:05

I\'m in the process of building a JavaScript / HTML5 game (using Canvas) for mobile (Android / iPhone/ WebOS) with PhoneGap. I\'m currently trying to design out how the UI a

3条回答
  •  渐次进展
    2020-12-31 14:30

    You can do it a million ways. However you feel most comfortable and your engineers feel most confident.

    If you're looking for inspiration or a code example, here's one way that I do it. I have a function that repeatedly draws a menu until a button is pressed. When the button is pressed, the game loads and the old menu click event listeners are removed and new game click event listeners are added. I also end the old draw loop of the menu and start a new game draw loop. Here's some selected snippets to give you the idea of how its done:

    Game.prototype.loadMenu = function() {
      var game = this;
      var can = this.canvas;
    
      // now we can use the mouse for the menu
      can.addEventListener('click', game.menuClickEvent, false);
      can.addEventListener('touchstart', game.menuClickEvent, false);
    
      // draw menu
      this.loop = setInterval(function() { game.drawMenu() }, 30);
    };
    
    Game.prototype.drawMenu = function() {
      // ... draw the menu
    }
    
    Game.prototype.loadLevel = function(levelstring) {
      // unload menu
      var can = this.canvas;
      var game = this;
      can.removeEventListener('click', game.menuClickEvent, false);
      can.removeEventListener('touchstart', game.menuClickEvent, false);
    
      if (this.loop) clearInterval(this.loop);
    
      // ... other level init stuff
    
    
      // now we can press keys for the game
      //can.addEventListener('click', game.gameClickEvent, false);
      can.addEventListener('touchstart', game.gameClickEvent, false);
      can.addEventListener('keydown', game.gameKeyDownEvent, false);
    
      this.loop = setInterval(function() { game.tick() }, 30);
    }
    
    // called from tick()
    Game.prototype.draw = function(advanceFrame) {
      // ...
    }
    

    This way I'm able to separate out game drawing and game events from menu drawing and menu events. It also gives me leeway to use game/animation elements in my menus should I want to make them look real pretty.

    (I posted this at the twin gamedev discussion too)

提交回复
热议问题