pauish
pauish

Reputation: 13

call method from another class from array of objects?

I´m doing an Arkanoid with P5 and I created a class Block, is just a constructor and a method draw.

class Block{
    constructor(widthBlock, heightBlock, x, y, colorBlock){
        this.widthBlock=widthBlock;
        this.heightBlock=heightBlock;
        this.x = x;
        this.y=y;
        this.colorBlock=colorBlock;
    }

    draw(){
        fill(this.colorBlock);
        rect(this.x, this.y, this.widthBlock, this.heightBlock);
        console.log('bloke');
    }
}

In the sketch class I filled the array called blocks and i call it on draw function but it throws this error sketch.js:25 Uncaught TypeError: Cannot read property 'draw' of undefined (line 25 is blocks[i].draw(); )

for(let i=0; i<=blockAmount; i++){
        for(let j=0; i<=5; i++){
            blocks.push(new Block(widthBlock*i, widthBlock*j ,widthBlock, 20, color('pink'))); 
            console.log(blocks.length);
        }
    }

function draw() {
    for(let i=0; i<=blocks.length; i++){
        //console.log('aasas');
        console.log(blocks[i]);
        blocks[i].draw();
        noLoop();
    }
}

Upvotes: 1

Views: 418

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173582

function draw() {
    for(let i=0; i<=blocks.length; i++){
        //console.log('aasas');
        console.log(blocks[i]);
        blocks[i].draw();
        noLoop();
    }
}

The problem is that you're iterating over blocks, but the i<=blocks.length condition causes the last loop iteration to evaluate blocks[blocks.length], which will be undefined.

To solve this, you can either correct the condition to i<blocks.length, or use for...of:

function draw() {
  for (const block of blocks) {
    block.draw();
    noLoop();
  }
}

Upvotes: 1

Prakhar Londhe
Prakhar Londhe

Reputation: 1471

You are checking i<=5 inside your second loop, you should be checking `j<=5'

for(let i=0; i<=blockAmount; i++){
        for(let j=0; i<=5; i++){
            blocks.push(new Block(widthBlock*i, widthBlock*j ,widthBlock, 20, color('pink'))); 
            console.log(blocks.length);
        }
    }

It prevents blocks array from getting more than 6 blocks because for all i greater than 5, the inner block doesn't run.

Upvotes: 0

Related Questions