0

I'm trying to make a shooting game with the view from above with javascript, here is the bullet object:

var Bullet = function(pId, bX, bY, bdX, bdY, bdT){
this.id = pId;
this.x = bX;
this.y = bY;
this.dx = bdX;
this.dy = bdY;
this.dt = bdT;

this.start = function (){
    this.valInt=setInterval(this.id+".muovi()", this.dt);
}

this.muovi = function(){
    this.x += this.dx;
    this.y += this.dy;

    this.img.style.left = this.x+'px';
    this.img.style.top = this.y+'px';
}
   this.img = new Image();
   this.img.src = "./img/sprites/bullet/bullet.png"
   this.img.style.position = "fixed"
   this.img.style.left = this.x + "px"
   this.img.style.top = this.y + "px"
   document.body.appendChild(this.img)
   this.start();
}

and then in the main js I instance it like this when an onkeydown event happen

function shootDx(){
b = new Bullet('b',pgX,pgY,1,0,1);
proj.push(b);
}

I want all the bullets inside an array so i can manage them better,there's a logic problem because when i shoot more than one time it doesn't create another instance, therefore i can't put them in the array and work on it, how can i afford that ?

  • Looks like your code already *is* putting them in an array. Where's the declaration of `proj`? – Pointy Feb 16 '17 at 18:22
  • Proj is just an empty array "var proj=[];" – Marco Panarelli Feb 16 '17 at 21:25
  • You can make multiple instances of the same class (constructor), but never of the same object :-P – Bergi Feb 16 '17 at 21:34
  • 1
    `setInterval(this.id+".muovi()", this.dt)` is not going to work. Use a proper function that you can pass to [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval#Syntax) - beware of [binding the context](http://stackoverflow.com/q/20279484/1048572) – Bergi Feb 16 '17 at 21:36
  • 1
    It *does* create another instance, you probably just didn't realise it. Also, make that `b` a local variable by adding `var`. – Bergi Feb 16 '17 at 21:38
  • @MarcoPanarelli OK then your code is definitely already adding the `Bullet` objects to an array. What is your question? – Pointy Feb 16 '17 at 21:38
  • In addition to the other comments, you should really define your object methods as `Bullet.prototype.start = function() { ... };`, and so on, rather than assigning them directly inside the `Bullet` object definition. – J. Titus Feb 16 '17 at 21:40

0 Answers0