P5.js issue - "bullet.push is not a function"

Hi there,

trying to follow this tutorial by TheCodingTrain on YouTube with some modification:

I keep getting the error “bullet.push is not a function”.

Any help is much appreciated.

Please see my sketch.js code below:

var character;
var scl = 20;
var projectile = [];
var bullet = [];

function setup() {
  createCanvas(1000, 1000);
  character = new Character();
  bullet = new Bullet(width/2, height/2);
  for (var i = 0; i < 5; i++) {
    projectile [i] = new Projectile(i*80+80, 60);
    
  }
}

function draw() {
  background(0,0,0);
  character.update();
  character.show();
   for (var i = 0; i < bullet.length; i++) {
    bullet[i].show();
    bullet[i].move();
  }
  
  for (var i = 0; i < 5; i++) {
    projectile [i].show();
  }
}

function keyPressed() {
  if (keyCode === LEFT_ARROW) {
    character.dir(-3, -3);
  } else if (keyCode === UP_ARROW) {
    character.dir(3, -3);
  } else if (keyCode === RIGHT_ARROW) {
    character.dir(3, 3);
  } else if (keyCode === DOWN_ARROW) {
    character.dir(-3, 3);
  }
  
if (keyCode === 32) {
       var bullet = new Bullet(character.x, height);
       bullet.push (bullet);
  }

}
  
function keyReleased() {
  if (keyCode === LEFT_ARROW) {
    character.dir(0, 0);
  } else if (keyCode === UP_ARROW) {
    character.dir(0, 0);
  } else if (keyCode === RIGHT_ARROW) {
    character.dir(0, 0);
  } else if (keyCode === DOWN_ARROW) {
    character.dir(0, 0);
  
  }
}
1 Like
  • @ var bullet = [];, you assign a new array to global variable bullet.
  • However, inside setup(), @ bullet = new Bullet(width/2, height/2);, you reassign global variable bullet w/ a new Bullet object.
  • It means global variable bullet no longer refers to an array, but a single instance of Bullet!
1 Like

Hi, thanks so much for your response. I’m not sure I fully understand though (I’ve just started learning p5.js and programming in general).

I found in the tutorial that i was following that the guy actually disabled that line of code with a comment like: //bullet = new Bullet(width/2, height/2);

I’m still getting the same error however. Any thoughts?

Does it happen when you hit space?

This time, you’re declaring a local variable named bullet within callback keyPressed() and assigning to it a new Bullet object.

However, a Bullet object isn’t an array! It’s got no method called push() either!

Either way, b/c bullet is a local variable, it ceases to exist when keyPressed() returns.

P.S.: I believe I’ve found the source code for that challenge tutorial video:

3 Likes

Thanks for your help! Managed to resolve it.