Vector2 and Dictionary in C++

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Karvalho
:warning: Old Version Published before Godot 3 was released.

How can I instantiate Vector2 and Dictionary in C++, and use Vector2 as keys in that dictionary?

I’ve tried this:

//MyMod.h
#include "dictionary.h"
#include "math_2d.h"

//MyMod.cpp
Dictionary dict = memnew(Dictionary);
Vector2* v = memnew(Vector2(1, 1));
dict[v] = 10;
return dict;

It compiles successfully, but inside Godot there’s no key Vector2(1, 1):

#Test.gd
var myMod = MyMod.new()
var dict = myMod.getDict()
print(dict[Vector2(1, 1)])

Returns an error: Invalid get index ‘1,1’

But this works:

//MyMod.cpp
Dictionary dict = memnew(Dictionary);
dict[1] = 10;
return dict;

and

#Test.gd
var myMod = MyMod.new()
var dict = myMod.getDict()
print(dict[1])

It prints 10, as expected.

So I’m obviously instancing Vector2 wrong. Or am I not? :smiley:

:bust_in_silhouette: Reply From: volzhs

I guess it’s because print(dict[Vector2(1, 1)]) makes new reference of Vector2, not pointing v of dict[v] = 10 in cpp.

did you try like this?

#Test.gd
var myMod = MyMod.new()
var dict = myMod.getDict()
for key in dict.keys():
    print(key, " : ", dict[key])

Weird. The result was:

True : 10

Somehow v was stored as a boolean. So I’m definitely instantiating Vector2 wrong?

Karvalho | 2016-04-12 18:34

:bust_in_silhouette: Reply From: Karvalho

I managed to make it work, but it has become a different problem now. I’ll make a new question, but just for closure.

This code doesn’t work as intended:

Vector2* v = memnew(Vector(1, 1));

But this code does:

Vector2 v = Vector2(1, 1);

But accordingly to this, I should always use memnew(). Or I’m mistaken?