how to best convert between Vector3 and Vector2?

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

I want to convert a Vector3 to a vector2 by removing one of the components.

For an array i would use array.remove(axis), however no such function exists for Vector3.
I know that Vector3 and vector2 do support other array like assignments: vector3[axis] = 1

The code that i am using now:

func get_vector2_from_vector3(vector3, axis):
	var vector2= Vector2(0,0)
	var i = 0
	var j = 0
	while i < 2:
		if j == axis:
			j += 1
		else:
			vector2[i] = vector3[j]
			i += 1
			j += 1
	return vector2

and

if (axis == 0):
    var vec2 = Vector2(vec3.y, vec3.z)
elif (axis == 1):
    var vec2 = Vector2(vec3.x, vec3.z)
elif (axis == 2):
    var vec2 = Vector2(vec3.x, vec3.y)

Is there simpler code for this? (preferably without loop or repetition of similar code)
If this is impossible, then i would like to know that as well

I use this and the opposite (Vector2 → Vector3) a lot, so any simpler code is welkom :slight_smile:

:bust_in_silhouette: Reply From: avencherus

Maybe I’m missing what you’re desiring, but generally I just do something like this:

var vec2 = Vector2(vec3.x, vec3.z)

This is indeed not exactly what i meant,
var vec2 = Vector2(vec3.x, vec3.z) requires that the y_axis is removed.

you did bring me on an idea:

if (axis = 0):
	var vec2 = Vector2(vec3.y, vec3.z)
elif (axis = 1):
	var vec2 = Vector2(vec3.x, vec3.z)
elif (axis = 2):
	var vec2 = Vector2(vec3.x, vec3.y)

Hytak | 2017-04-20 20:00

Oh ok, now I understand what you meant by returning an axis. You want a function that can selectively capture one plane, choosing one of the three combinations of axes to form the basis.

And, quite right, looks like you found your own solution. I hope that idea cleaned some things up for you.

avencherus | 2017-04-21 08:52

:bust_in_silhouette: Reply From: Hytak

I found a solution myself:

func vec2_vec3(vec3, axis):
	var array = [vec3.x, vec3.y, vec3.z]
	array.remove(axis)
	return Vector2(array[0], array[1])

func vec3_vec2(vec2, axis, value):
	var array = [vec2.x, vec2.y]
	array.insert(axis, value)
	return Vector3(array[0], array[1], array[2])

This doesn’t use any gd loops, and also uses no repetition of similar code.
It does use an extra array…