对象原型在Canvas Game中不起作用
Object Prototyping not working in Canvas Game
所以我正在写一个愚蠢的小画布游戏,主要是小行星的副本。无论如何,我已经设置了按钮监听器,这样当用户按下空格键时,播放器对象的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
完整的代码在我的网站上,这里是
另一个编辑:
Chrome控制台说,这种类型的错误发生在第122行,这恰好是代码片段:
context.drawImage(this.sprite,this.x,this.y);
然而,我不确定那里怎么会有类型错误,精灵是一个图像,X和Y值没有定义,它们是数字。
您在哪里调用绘图函数?我敢打赌,您正在调用bullet.draw();
,而不是在实际的子弹头实例上调用它。
有点像之间的区别
Cat.meow();
和
var mittens = new Cat();
mittens.meow();
相关文章:
- electronic BrowserWindow的最小高度和宽度在hide()show()方法之后不起作用
- 监视函数从服务返回不起作用,但作用域函数起作用
- 幻灯片滚动javascript不起作用
- 简单的javascript在Shopify中不起作用
- Recaptcha在IE7和IE8中不起作用
- Ember Data DS.Model's set函数不起作用
- JsFiddle上的鼠标事件不起作用
- 我的AngularJS表达式没有'不起作用
- 点击按钮输入不起作用
- 面向对象的Javascript代码在IE7中不起作用
- 分部隐藏在jquery中不起作用
- 在phonegap应用程序内部重定向不起作用
- Array.length似乎不起作用;console.log则显示其他情况
- $ionicplatform内的$scope不;不起作用
- 我的javascript for循环不起作用
- Meteor-添加用户自定义字段的方法不起作用
- 为什么 .focus() 不起作用,而 .css(“color”,“red”) 在同一个选择器上起作用
- Textarea必需的attribut在javascript中不起作用
- 为什么javascript:void(0)在Firefox中不起作用
- 对象原型在Canvas Game中不起作用