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

2024/5/22

Help with contructing a world with objects in a square pattern / line

Konsti Konsti

2024/5/22

#
I am currently making a game for a school project. I wanted to implement code in the constructor (myWorld), to spawn a specific object multiple times in a square / rectangle pattern with a 48 pixel gap between each object to construct my map automatically so that I don't have to write 2 lines of code for each instance of the object manually. PLEASE tell me how I can do that and also maybe also how spawn objects in a line / array, because I've looked everywhere, but I can't seem to find any answers or maybe I'm just to stupid. i hope danpost hears my cry for help
danpost danpost

2024/5/23

#
Let us say your specific object is from a class called Logo. Then to add one Logo instance into the world, you would use this:
addObject(new Logo(), 24, 24);
which is the same exact thing as this:
int x0 = 24;
int y0 = 24;
Actor actor = new Logo();
addObject(actor, x0, y0);
To add a dimension to this (to create a line of Logo instances), you will need to repeatedly vary the location coordinates at which the object is placed. A for loop is perfect for this. However, I think you want the gap between the edges of the images to be 48, not the gap between the center of the images. So, start with this:
int spacing = 48+(new Logo()).getImage().getWidth();
This gets the value needed to space them properly. Then, the loop would be:
for (int x=spacing/2; x<getWidth(); x+=spacing) addObject(new Logo(), x, y0);
To add another dimension, add another loop to vary along the vertical. This probably will require another spacing variable (one variable for each direction -- maybe spacingX and spacingY).
Konsti Konsti

2024/6/5

#
Ooooh my god thank you so much. Hard-coding levels manually would've been extremely tedious and this helps a lot. Gonna try this out now thank you so much
You need to login to post a reply.