0
\$\begingroup\$

Basically I have a function that I need to create an object of every time the user presses space(event listeners not shown here).

function arrow(){
    this.x = playerXPos + 40;
    this.y = playerYPos + 40;

    this.init = function(){
        var arrowImg = new Image();
        arrowImg.src = "arrow.png";
        c.drawImage(arrowImg,this.x,this.y);

        this.x+=10;

        if(this.x > 500){
            keySpace = false;
        }
    }
}

if(keySpace){
    arrowObj.init();
}

This works great, but I can only have 1 arrow on the screen at once, which is rather limiting. Is there some way to create a new object every time the if statement is true, and store it in an array or something?

\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

You can use new to create a new object, initialize it and then store it in an array

// declare this array in a scope that persists (e.g. global scope or in a closure)
var arrows = [];

if(keySpace){
    // create new arrow, initialize it and store it in the array of arrows
    var newArrow = new arrow();
    newArrow.init();
    arrows.push(newArrow);
}
\$\endgroup\$
1
  • \$\begingroup\$ Yes, but you'll also need to draw all the arrows each frame, and remove arrows from the list when they're not needed any more. Removing things is often more challenging than adding them, because you need to do it in a safe way while iterating the list. \$\endgroup\$
    – MarkR
    Commented Feb 13, 2013 at 11:27
2
\$\begingroup\$

You could also do more or less the same thing, but alocate a fixed size array from start and then just fetch one that isent in use. This is much more memory friendly.

this is called memory pools.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ +1 for Pool. Projectiles should always be stored in a Pool in a memory managed application. \$\endgroup\$
    – jgallant
    Commented Feb 13, 2013 at 11:46
  • \$\begingroup\$ -1 for Pool, it's a premature optimisation. You probably don't need it ever and definitely don't need it yet. \$\endgroup\$
    – MarkR
    Commented Feb 13, 2013 at 16:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .