【问题标题】:Object Prototyping not working in Canvas Game对象原型在画布游戏中不起作用
【发布时间】:2012-07-25 03:30:40
【问题描述】:

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

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

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

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 = function 更改为function bullet 并将bullet.prototype.draw 更改为bullet.draw 后,我仍然收到错误消息。这一次,更神秘,说

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

完整的代码在我的网站上,here

另一个编辑:

Chrome 控制台说这个类型错误发生在第 122 行,恰好是代码的 sn-p:

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

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

【问题讨论】:

  • 您确定this.sprite 是在您将其传递给context.drawImage 时定义的吗?尝试先添加console.log(this.sprite) 进行检查。 b_sprite 定义是否正确?
  • 是的,正在通过。我已经以var b_sprite = new Image(); b_sprite.src = "bullet.png"; 的格式定义了我所有的精灵

标签: javascript canvas prototype-programming


【解决方案1】:

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

有点区别

Cat.meow();

var mittens = new Cat();
mittens.meow();

【讨论】:

  • 这基本上是正确的,我的“引擎”(eGi)执行绘制函数的糟糕方式是使用我传递给它的“名称”,在这种情况下恰好是子弹,与类名相同。我一直在使用 Objective-C 太多,子弹必须是全局的,我的“引擎”才能识别它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
相关资源
最近更新 更多