0 votes

Lets say I want to modify a bunch of Vector3 variables and I want to change each of their x, y, and z values independently. Right now I have to either write the same code out three times, once for each axis, or create a function and pass into it a whole ton of variables. This isn't a big deal but it has been bothering me... It seems like there must be a way to do it!

Examples; what I am doing now:

if(foo.x > 5):
    bar.x = foo.x
    eggs.x += bar.x
    foo.x = ham.x

if(foo.y > 5):
    bar.y = foo.y
    eggs.y += bar.y
    foo.y = ham.y

if(foo.z > 5):
    bar.z = foo.z
    eggs.z += bar.z
    foo.z = ham.z

I would love to do something like this but I can't figure out how to make it happen:

for axis in xyz:
    if(foo.axis > 5):
        bar.axis = foo.axis
        eggs.axis += bar.axis
        foo.axis = ham.axis

Thank you!!!

Godot version 3.3
in Engine by (251 points)

2 Answers

+1 vote
Best answer

this wont be faster but should be working

var xyz = ["x","y","z"]

for axis in xyz:
    if(foo.get(axis) > 5):
        bar.set(axis, foo.get(axis))
        eggs.set(axis, eggs.get(axis) + bar.get(axis))
        foo.set(axis, ham.get(axis))

This is actually wrong!

Have a look at timothybrentwood answer below!

by (4,078 points)
edited by

Yeah, it's better than what I was doing though! Thank you!

This shouldn't work on Vectors since they don't have a get() method.

0 votes

You can access x, y, and z using the [] operator:

for component in range(3):
    if foo[component] > 5:
        bar[component] = foo[component] 
        eggs[component] += bar[component] 
        foo[component] = ham[component] 
by (3,870 points)
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.