GETTING STARTED IN GODOT – PART 8 – PRACTICE WITH VECTORS

 

In this practice guide, we will look at vectors - a type of object that is commonly used in Godot and several other programming languages. 

 

We will briefly look at Vector2 but there is also Vector2i and Vector3.

 

A Vector2 is simply an object that contains 2 two float numbers as information.  Because Vector2 objects tend to hold cartesian information, the two numbers are called x and y.

 

1.     Let’s start with some temporary practice.  Go to the _ready function and create a Vector2 object named coco.  Then print it out to the screen.  Here is the code needed:

var coco = Vector2(1.50, 7.25)

print(coco)

 

 

2.     Run your game.  You should see the values of coco outputted.

3.     Let’s try changing the two values in coco.

coco.x = 2.2

coco.y = 8.9

print(coco)

 

 

4.     Again, run your game and you will see the new values of coco outputted.  Easy enough right?

 

5.     Let’s increase both values in coco by 10.  We’ll do this in two different ways.

coco.x = coco.x + 10

   coco.y += 10

     print(coco)

 

 

6.     Again, run your code to make sure things work like expected.

 

7.     Let’s erase everything in the _ready method and creating a Vector3 object with values 6, 9 and 8.  Test the following code out:

 

 

 

8.     We can also find the distance between two Vector2 objects.  Here’s some example code that you can try:

 

 

 

9.     Vectors have a snapped method that can be use to return a new vector that is snapped to a grid.

In the following code, the vector spos gets the values of vector pos but snapped to a grid.  This will be useful later on.

 

 

10.  That’s it.  Remove everything from the _ready function.  Add the pass statement.