0

所以我正在写一个愚蠢的小画布游戏,主要是一个小行星的副本。无论如何,我设置了按钮侦听器,以便当用户按下空格键时,将fire()调用播放器对象的函数:

eGi.prototype.keyDownListener = function(event) {
    switch(event.keyCode) {
        case 32:
            player.fire();
            break;

在 fire 函数中,我的脚本检查进程是否已经在运行,如果没有,则创建一个新的“bullet”对象,将其存储在临时变量中,并将其添加到绘图堆栈中。

fire:(function() {
    if (this.notFiring) {
        var blankObject = new bullet(this.x,this.y,this.rot,"bullet");
        objects.push(blankObject);
        timer2 = setTimeout((function() {
            objects.pop();
        }),1000);
        this.notFiring = false;
    }}),

(顺便说一句,当用户释放空格键时,this.notFiring它被设置回 true。)

这是子弹对象构造函数及其必需的原型方法,draw(context)

var bullet = function(x,y,rot,name) {
    this.x = x;
    this.y = y;
    this.sx = 0;
    this.sy = 0;
    this.speed = 1;
    this.maxSpeed = 10;
    this.rot = rot;
    this.life = 1;
    this.sprite = b_sprite;
    this.name = name;
}
bullet.prototype.draw = function(context) {
    this.sx += this.speed * Math.sin(toRadians(this.rot));
    this.sy += this.speed * Math.cos(toRadians(this.rot));
    this.x += this.sx;
    this.y -= this.sy;
    var cSpeed = Math.sqrt((this.sx*this.sx) + (this.sy * this.sy));
    if (cSpeed > this.maxSpeed) {
        this.sx *= this.maxSpeed/cSpeed;
        this.sy *= this.maxSpeed/cSpeed;    
    }
    context.drawImage(this.sprite,this.x,this.y);
}

无论如何,当我运行我的游戏并按下空格键时,Chrome 开发者控制台给了我一个错误,上面写着:

Uncaught TypeError: Object function (x,y,rot,name) {
    this.x = x;
    this.y = y;
    this.sx = 0;
    this.sy = 0;
    this.speed = 1;
    this.maxSpeed = 10;
    this.rot = rot;
    this.life = 1;
    this.sprite = b_sprite;
    this.name = name;
} has no method 'draw'

即使我做了原型。我究竟做错了什么?

编辑:

更改var bullet = functionfunction bullet并更改bullet.prototype.draw为后bullet.draw,我仍然收到错误消息。这一次,更神秘,说

Uncaught TypeError: type error
    bullet.draw
    (anonymous function)
    eGi.drawObjs
    eGi.cycle

完整的代码在我的网站上,在这里

另一个编辑:

Chrome 控制台说这种类型的错误发生在第 122 行,这恰好是代码片段:

context.drawImage(this.sprite,this.x,this.y);

但是,我不确定那里怎么可能出现类型错误,精灵是一个图像,X 和 Y 值不是未定义的,它们是数字。

4

1 回答 1

1

你在哪里调用你的绘图函数?我打赌你是在打电话bullet.draw();而不是在实际的子弹实例上调用它。

有点像之间的区别

Cat.meow();

var mittens = new Cat();
mittens.meow();
于 2012-07-25T04:54:29.467 回答