Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

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);
}
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  
+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

 
discard

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.