0 votes

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 :)

in Engine by (55 points)
edited by

2 Answers

+1 vote
Best answer

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..

by (55 points)
+1 vote

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

var vec2 = Vector2(vec3.x, vec3.z)
by (5,274 points)

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)

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.