在JavaScript中试验对象

时间:2014-06-09 23:11:37

标签: javascript oop html5-canvas

我几天前开始在Codecademy上学习JavaScript,并以Lost Decade的Simple Canvas Game为基础,我想知道:我怎么能添加多个敌人?我知道这是可能的,但是我很难让它发挥作用。

Here's my code before I broke everything.

编辑:我已经为这个怪物添加了动作,但不确定是否创建了另一个怪物并让我的功能与它们相配。

1 个答案:

答案 0 :(得分:1)

目前您有一个单例对象monster,并且所有函数调用都直接操作该对象的属性。 monster与所有函数在同一范围(全局范围)中声明,因此可以毫无问题地访问它。

创建>至少你需要重写所有函数以接受一个monster对象,然后你可以通过将那个怪物作为参数传递来操纵每个属性,例如。

var changeMonsterDirections = function(theMonster) {
    for (var i = 0; i < 2; i++) {
            theMonster.directions[i] = directions[Math.floor(Math.random() * directions.length)];
    }
    // If both directions are the same, null out one of them so that
    // the monster doesn't move twice as fast
    if (theMonster.directions[0] == theMonster.directions[1]) {
            theMonster.directions[1] = null;
    }

}

然后,如果你有

var monster1 = {
    speed: 200,
    directions: [null, null]
};
var monster2 = {
    speed: 200,
    directions: [null, null]
};

你可以将它们传递给你的函数,就像这样

changeMonsterDirections(monster1);
changeMonsterDirections(monster2);

以上内容适用于您编写的程序,但不是面向对象或良好的编程习惯。关于如何使用适当的OOP使游戏正常工作的讨论超出了SO - try

的范围

http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/

或类似的,谷歌为其他人。祝你好运。