4.5.1
I want to loop through all instantiated GreyBlocks in the scene. Then be able to determine their x,y locations so I can use them in a RectsOverlap function, if there is one, for custom collision.
There is a separate object which is my character which will also be used in the collision check.
How can I do this?
Here is how I instantiate the grey blocks. They are instantiated according to what is stored in the LevelArray.
for (int x = 0; x < 30; x++)
{
for (int y = 0; y < 16; y++)
{
if (levelArray[x, y] == 2)
{
PackedScene joeScene = (PackedScene)ResourceLoader.Load("res://GameObjects/joe.tscn");
Joe = (Joe)joeScene.Instantiate();
Joe.x = x * 64f;
Joe.y = y * 64f;
Joe.Position = new Vector2((float)(Joe.x), (float)(Joe.y));
AddChild(Joe);
}else if (levelArray[x, y] == 1)
{
PackedScene greyBlock = (PackedScene)ResourceLoader.Load("res://GameObjects/grey_block.tscn");
GreyBlock gb = (GreyBlock)greyBlock.Instantiate();
gb.x = x * 64f;
gb.y = y * 64f;
gb.Position = new Vector2(gb.x, gb.y);
AddChild(gb);
}
}
}
You can add a list (or an array, depending on your needs, but I guess a list is more convenient to use for prototyping), and then use a foreach loop (or a for loop, it’s as you want).
Something like this:
List<GreyBlock> greyBlocks = new();
PackedScene greyBlockPrefab = (PackedScene)ResourceLoader.Load("res://GameObjects/grey_block.tscn");
greyBlocks.Add(greyBlockInstance);
foreach (GreyBlock greyBlock in greyBlocks) {
// TODO: Do something on greyBlock
}
The idea should be pretty simple: loop through the blocks, and register the furthest coordinates in all 4 directions. Once you’re done, check if your player position is contained inside these coordinates; if that’s the case, that would mean the player is inside the rect formed by the blocks.
I’m using custom collisions as my tile collision works perfectly when I do it this way. Plus I’m converting code from GameMaker and I’m still unfamiliar with the Godot Collision system.
If I want to iterate a list declared and populated in Main.cs which is attached to the Main.tscn, in a Object called Joe.tscn with a script Joe.cs how would I do that?