GDScript 2D Array Tutorial – Complete Guide

In the dynamic world of game development, mastering efficient, and flexible data arrangements can be a game changer. This is true even more for 2D arrays. If you’re a game development enthusiast, hobbyist, or a professional, this tutorial is perfect for you. Let’s dive into the world of GDScript 2D arrays and explore its potential to build amazing games.

What are 2D arrays?

In simple terms, a 2D array is a tool used to organize elements in a table with rows and columns. Much like a grid, where each cell can hold unique values.

What are they used for?

From plotting player movements to managing complex game logic, to storing level data, 2D arrays serve plenty of purposes. With efficient use of 2D arrays you can optimize performance and make your game project more manageable.

Why should I learn about 2D arrays?

Learning how to use 2D arrays could be a significant skill to level up your game development abilities. Apart from providing an efficient way to handle data, it can also open doors to sophisticated game mechanics, complex algorithm implementation, and greater control over game dynamics.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

An Introduction to GDScript 2D Arrays

Let’s start off by creating a blank 2D array. In this example, we will also show how to set the number of rows and columns.

var array2D = []
for i in range(5): 
  array2D.append([])
  for j in range(5): 
    array2D[i].append(0)

This snippet creates a 2D array with five rows and five columns, and initializes all elements to zero. The outer ‘for’ loop here indicates the number of rows and the inner ‘for’ loop indicates the columns.

Populating Your 2D Array

What if you want to assign specific values to your 2D array elements? Here’s how:

for i in range(5):
  for j in range(5): 
    array2D[i][j] = i * j

This code sets each element of the 2D array to the product of its row and column indices. For example, the value at row 3 and column 2 in our 2D array will now be 6 (3 x 2).

Accessing Elements in Your 2D Array

Accessing elements in a 2D array is simple as well. Let’s print a value from our grid-like structure.

print(array2D[2][3]) # This will print the value at row 2 and column 3

Manipulating 2D Arrays

2D arrays can be manipulated much like any other array. For example, you can use the append() method to add an additional row.

array2D.append([10, 20, 30, 40, 50]) # This will add an additional row to the bottom

To remove an element from the 2D array, you can use the remove() method as shown below.

array2D[2].remove(1) # This will remove the second element from third row.

And that’s a wrap for now! With these basics, you can start harnessing the power of 2D arrays in your GDScript game projects!

Iterating Over 2D Arrays

Displaying the content of 2D arrays is simple and can be achieved using nested loops. Here’s how:

for i in range(len(array2D)):
  for j in range(len(array2D[i])): 
    print(str(array2D[i][j]) + " ", end="")
  print()

This nested loop will go through each row and column of our 2D array and print its content. The outer loop iterates over each row, while the inner loop focuses on elements in each row (or column).

Slicing 2D Arrays

Slicing allows you to work with subsets of a 2D array. Let’s extract a 3×3 sub-array from our original 2D array.

var subarray2D = []
for i in range(1,4):
  subarray2D.append(array2D[i][1:4]) 
print(subarray2D)

This code creates a sub-array with rows ranging from the second to the fourth, and columns also ranging from the second to fourth elements. Note that array indices start at 0, so when we say the 2nd row, it translates to the index 1.

Working with Multi-Dimensional Arrays

Just as you can work with 2D arrays, you can also work with arrays that are even more complex. These are called multi-dimensional arrays. Let’s extend our 2D array to a 3D array.

var array3D = []
for i in range(3):
  array3D.append([])
  for j in range(3):
    array3D[i].append([])
    for k in range(3):
      array3D[i][j].append(i*j*k)

This code creates a 3x3x3 array, each element of which is the product of its row, column, and depth indices.

Hopefully, with these hands-on examples and descriptions, you have gained an understanding of how to use and manipulate 2D arrays in GDScript. It’s time to put these resources into practice and enhance your game development skills with GDScript 2D arrays!

Adding More Depth to Your Arrays

As you’ve seen, arrays can go beyond just two dimensions. Let’s examine a 4D array. This array could, for example, represent a time-lapse of 3D positions across a game map.

var array4D = []
for i in range(3):
  array4D.append([])
  for j in range(3):
    array4D[i].append([])
    for k in range(3):
      array4D[i][j].append([])
      for l in range(3):
        array4D[i][j][k].append(i*j*k*l)

With these nested loops, we’ve created a 4D array where each element represents a position (x, y, z) on our 3D game map at a specific time (t).

Working with Arrays of Arrays (AoA)

Another pattern that you may find helpful involves arrays of arrays, or AoA. In this case, each row can have variable length, depending on what data each row is supposed to hold. An AoA could be useful for game levels that have varying numbers of enemies or items, for instance.

var AoA = [[1, 2, 3], [4, 5, 6, 7, 8], [9, 10]]

Here, the second row (or sub-array) in the AoA has more elements than the first and third rows. This flexibility in size can be very useful in certain circumstances.

Array Functions and Methods

GDScript provides various functions and methods to manipulate arrays. For example, you can use the size() method to get the size of an array:

print(array2D.size())

You can use the insert() method to insert an element at a specific position. Below, we insert a new row at index 2:

array2D.insert(2, [8, 10, 15, 20, 25])

And you can use the find() method to get the index of the first occurrence of an element. The following prints the index of the first occurrence of the number 15 in the third row:

print(array2D[2].find(15))

We hope these examples and the introduction to GDScript 2D arrays have been insightful and helpful for your game development journey. Be sure to practice how to create, maintain, and manipulate these 2D arrays so that you can efficiently handle in-game data.

Where to Go Next?

Now that you’ve gotten a good introduction to 2D arrays in GDScript, where should you go from here? What’s the next step in your game development journey?

We recommend checking out our Godot Game Development Mini-Degree program. This comprehensive collection of courses is designed to help beginners and more experienced developers alike to build cross-platform games using the lightweight and open-source Godot engine. Topics covered include using 2D and 3D assets, learning GDScript, mastering gameplay control flow, and much more. There are hands-on projects included to help build up your portfolio of Godot projects.

If you’re looking for a broader collection, our library of Godot Courses is worth a visit as well. Zenva offers a range of beginner to professional courses in programming, game development, and AI, along with learning paths that can take you from coding novice to professional developer. Happy coding!

Conclusion

2D arrays in GDScript are an invaluable tool for any aspiring game developer. From designing intricate game maps to managing complex game logic, their applications are vast and versatile. Mastering them can significantly enhance your game development skills and bring your concepts to life with greater efficiency and control. We encourage you to continue exploring and experimenting with 2D arrays as you bring your game world to life.

In case you’re just getting started or you’re looking to deepen your expertise, we at Zenva offer a wealth of resources to support your learning journey. One such resource is our Godot Game Development Mini-Degree program. It is designed to provide you with comprehensive guidance, from beginner steps to advanced 2D and 3D game creation with this dynamic game engine. We hope you’ll join us as we explore the possibilities of GDScript and Godot game development.

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.