This site requires JavaScript, please enable it in your browser!
Greenfoot back
kartikitrak
kartikitrak wrote ...

2012/5/3

Array of Objects-Help

kartikitrak kartikitrak

2012/5/3

#
Hello. I am fairly new to Greenfoot so pardon my noob-ish knowledge. Basically all I want is to make an array of objects. These objects will be side by side and will be used for my game's floor that I have already coded to prevent the user from falling through. Each object is a square and basically depending on the level, the pattern I would like the floor to be will be different. For example if: = 1 block. I would like it to form . Instead of manually placing the coordinates of each object I would like an array that I can eventually configure to space it out. This is roughly the same code I'm using to make my "array" which is providing me with Null Pointer Exception Errors.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class Screen extends World
{

    /**
     * Constructor for objects of class Screen.
     * 
     */
    public Screen()
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(600, 400, 1); 

        block[] blockArray = new block[5];
        for (int i = 0; i< 5; i++)
        {
            addObject(blockArray[i],(287+(5*i)), 488);
        }
    }
}

Thank you.
danpost danpost

2012/5/3

#
Line 15 just tells the compiler of your intent to store 5 blocks, however, does not create them. Instead, make line 15
block[] blockArray = { new block(), new block(), new block(), new block(), new block() };
kartikitrak kartikitrak

2012/5/3

#
Thanks so much! That worked perfectly. Now what if I wanted 100 blocks. Would I need to copy the new bock() 100 times or is there another way. Again, thank you for such a quick reply!
danpost danpost

2012/5/3

#
It is really not neccessary to create the array of block to begin with, use
for (int i = 0; i< 100; i++)
{
    addObject(new block(),287+(5*i)), 488);
}
kartikitrak kartikitrak

2012/5/3

#
Thank you! I am grateful.
You need to login to post a reply.