So I'm writing a silly little canvas game, mainly a copy of Asteroids. Anyway, I have my button listener set up so that when the user presses the spacebar, the player object's fire()
function is called:
eGi.prototype.keyDownListener = function(event) {
switch(event.keyCode) {
case 32:
player.fire();
break;
In the fire function, my script checks if the process is already running, and if not, then it creates a new "bullet" object, stores it in a temporary variable, and adds it to a draw stack.
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;
}}),
(By the way, when the user releases the spacebar, this.notFiring
is set back to true.)
This is the bullet object constructor and its required and prototyped method, 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);
}
Anyway, when i run my game and press the spacebar, the Chrome developer console gives me an error that says:
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'
even though i prototyped it. What am I doing wrong?
EDIT:
after changing var bullet = function
to function bullet
and changing bullet.prototype.draw
to bullet.draw
, I still get an error. This time, it's more mysterious, saying
Uncaught TypeError: type error
bullet.draw
(anonymous function)
eGi.drawObjs
eGi.cycle
the full code is up on my website, here
ANOTHER EDIT:
The Chrome console says that this type error occurs on line 122, which happens to be the snippet of code:
context.drawImage(this.sprite,this.x,this.y);
however, i'm not sure how there could be a type error there, the sprite is an Image, and the X and Y values are not undefined, they are numbers.
Where are you calling your draw function? I'm betting you're calling bullet.draw();
instead of calling it on an actual bullet instance.
Kinda like the difference between
Cat.meow();
and
var mittens = new Cat();
mittens.meow();