Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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";


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


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?

share|improve this question

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 = [];

    // create new arrow, initialize it and store it in the array of arrows
    var newArrow = new arrow();
share|improve this answer
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. – MarkR Feb 13 '13 at 11:27

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.

share|improve this answer
+1 for Pool. Projectiles should always be stored in a Pool in a memory managed application. – Jon Feb 13 '13 at 11:46
-1 for Pool, it's a premature optimisation. You probably don't need it ever and definitely don't need it yet. – MarkR Feb 13 '13 at 16:00

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.