首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Javascript画布游戏引擎

Javascript画布游戏引擎
EN

Code Review用户
提问于 2015-06-19 00:17:29
回答 1查看 366关注 0票数 6

我正在JavaScript中创建一个简单的2D帆布游戏引擎。我是否可以进行任何优化,或者您可以看到明显的问题(性能、语义或其他方面)?

JS Bin在这里

代码语言:javascript
运行
复制
var GameCanvas = {
    // GameCanvas Variables
    animation: {
        requestAnimationFrame: null,
        halt: false
    },
    canvas: {
        element: null,
        context: null,
        width: 500,
        height: 500,
        backgroundColor: '#000000'
    },

    objects: [

    ],

    baseObject: function(){
        return {
            // Custom internal name of object (Mostly for debugging)
            name: '',
            position: {
                width: 0,
                height: 0,
                x: 0,
                y: 0
            },
            // Any custom data for this object
            data: {
            },
            // the draw method

            draw: function(GameCanvas){

            },
            criticalObj: true
        };
    },

    addObject: function(obj){
        this.objects.unshift(obj);
    },


    init: function(CanvasID){
        // Get Canvas by ID
        this.canvas.element = document.getElementById(CanvasID);
        if(this.canvas.element===null){
            this.console.error("No valid canvas with ID \""+CanvasID+"\" found.");
            return false;
        }

        // Get Canvas dimensions
        this.canvas.width = this.canvas.element.width || this.canvas.width;
        this.canvas.height = this.canvas.element.height || this.canvas.height;

        // Get the context
        this.canvas.context = this.canvas.element.getContext('2d');
        if(this.canvas.context===null){
            this.console.error("Failed to get context.");
            return false;
        }

        // Setup Request Animation Frame
        // RequestAnimationFrame Shim
    this.animation.requestAnimationFrame = (function(){
      return  window.requestAnimationFrame       ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame    ||
        function(callback){
                  //hack for RequestAnimationFrame not being there
                  this.console.log('No support for RequestAnimationFrame.');
          window.setTimeout(callback, 1000 / 60);
        };
     })();

        this.console.log("Initialized Successfully.");
        return true;
    },

    console: {
        data: '',
        // Allows for custom error output
        error: function(data){
          if(console.error!==undefined){
              console.error('GameCanvas: '+String(data));
          }
            this.data += data+"\n";
      },
        log: function(data){
          if(console.log!==undefined){
              console.log('GameCanvas: '+String(data));
          }
            this.data += data+"\n";
      }
    },

    run:function(){
        this.console.log("Starting mainLoop().");
        this.mainLoop();
  },

    mainLoop: function(){
        // Fill Background
        this.canvas.context.fillStyle = this.canvas.backgroundColor;
        this.canvas.context.fillRect(0,0,this.canvas.width,this.canvas.height);

        //Loop through objects
        for(var obj in this.objects){
            try{
                this.objects[obj].draw(this);
            }
            catch(err){
                this.console.log("Object "+this.objects[obj].name+":"+obj+" throws error:\n"+err);
                if(this.objects[obj].criticalObj){
                    this.console.error("Critical Object "+this.objects[obj].name+":"+obj+" not drawn. Halting mainLoop().");
                    this.animation.halt = true;
                }
            }
        }

        // Looping call
        if(!this.animation.halt){
          this.animation.requestAnimationFrame.call(
            window, // Call function in context of window

            // Call the mainLoop() function in the context of the current object
              this.mainLoop.bind(this)
          );
        }
        else{
            this.console.log("mainLoop() halted.");
            this.animation.halt = false;
        }
    }
};

GameCanvas.init("canvas");

var box = GameCanvas.baseObject();
box.name = "Box";
box.draw = function(GameCanvas){
    GameCanvas.canvas.context.fillStyle = "#00FF00";
    GameCanvas.canvas.context.fillRect(this.position.x,this.position.y,this.position.width,this.position.height);
};
box.position.width = 50;
box.position.height = 50;
box.position.x = 10;
box.position.y = 10;

GameCanvas.addObject(box);
GameCanvas.run();
EN

回答 1

Code Review用户

回答已采纳

发布于 2015-07-09 23:06:03

有些地方有一些奇怪的间距,比如空数组和函数。例如,下面的代码块可以更改为objects: []

对象:undefined

对于空函数也是如此,如下所示:

绘制:函数(GameCanvas){}

你的一些缩进也是不一致的。例如,下面的代码块,以及具有不一致缩进的代码块:

函数(回调){ //hack表示RequestAnimationFrame不在那里--this.console.log(“不支持RequestAnimationFrame.”);window.setTimeout(回调,1000 / 60);}

应该改为更一致的风格,如下所示:

代码语言:javascript
运行
复制
function(callback){
    //hack for RequestAnimationFrame not being there
    this.console.log('No support for RequestAnimationFrame.');
    window.setTimeout(callback, 1000 / 60);
}

我个人建议在Javascript中使用四个空格或一个选项卡作为缩进。

this.console.log("Object "+this.objects[obj].name+":"+obj+" throws error:\n"+err);行中,您可以在console.log前面加上this。在这种情况下,不需要this,可以删除它。

最后,您还有许多其他的风格违规行为,因此我建议查看样式指南,比如这一个,以获得关于如何正确编写样式代码的参考。

票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/94035

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档