0 votes

I'm trying to make Godot do a simple search within a 2d area, but it never seems to work and I'm wondering if it's because if there are too many 'and's in an if statement, that it's just breaking it. Here's what I have:

vec is a Vector2 position from a node.

area is an array with [x1,x2,y1,y2]. My boundary lines.

if vec.x > area[0] and vec.x < area[1] and vec.y > area[2] and vec.y < area[3]:
        print("---Stuff in the way ---")
Godot version 3.3
in Engine by (355 points)

Four ands are not going to break an if statement. I don't see anything wrong with your code. There's probably something wrong with one of the variables. Also, you can use Rect2's has_point method to accomplish what you want with no ands.

Thanks for your input.

1 Answer

0 votes

It's not possible to have too many ands in an if statement. Rewrite the code like this and you can see where it's failing:

if vec.x <= area[0]:
    printt("x1 fail", vec, area)
elif vec.x >= area[1]:
    printt("x2 fail", vec, area)
elif vec.y <= area[2]:
    printt("y1 fail", vec, area)
elif vec.y >= area[3]:
    printt("y2 fail", vec, area)
else:
    print("---Stuff in the way ---")

You can replace the printt() statements with pass statements once you figure out where in your code the issue is coming from.

As a general rule of thumb, you want to have only one boolean operator (and or or) per if condition in order to keep your code clean and readable. Writing deductive if statements such as the one I wrote above is a great way to make code more readable and maintainable.

by (3,707 points)
edited by

"This code is also slightly more performant because as soon as one condition fails it doesn't evaluate the rest of the conditions"

gdscript (and most other language) does short circuiting, which means as soon as the condition fails the and is not evaluated.

Also the if can be cleaned up using ().

E.g.

if (vec.x > area[0] and vec.x < area[1]) and (vec.y > area[2] and vec.y < area[3]):
    ....
    pass

Thank you wyattb! I am aware of what short circuiting is, but I wasn't aware that gdscript used short circuiting. I edited my answer accordingly.

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 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 webmaster@godotengine.org with your username.