+1 vote

Does anyone knows how to write this loop in GDScript:

for (var ix = 0, iy = 0; ix < nx || iy < ny;)?

Code example:

function walk_grid(p0, p1) {
var dx = p1.x-p0.x, dy = p1.y-p0.y;
var nx = Math.abs(dx), ny = Math.abs(dy);
var sign_x = dx > 0? 1 : -1, sign_y = dy > 0? 1 : -1;

var p = new Point(p0.x, p0.y);
var points = [new Point(p.x, p.y)];
for (var ix = 0, iy = 0; ix < nx || iy < ny;) {
    if ((0.5+ix) / nx < (0.5+iy) / ny) {
        // next step is horizontal
        p.x += sign_x;
        ix++;
    } else {
        // next step is vertical
        p.y += sign_y;
        iy++;
    }
    points.push(new Point(p.x, p.y));
}
return points;

}

Thanks!

asked Nov 5, 2018 in Engine by pospathos (236 points)

What language is that?

Looks like JavaScript to me.

1 Answer

+1 vote
Best answer

At a glance it seems to be a short form of two nested for loops, but I think it could more easily be done with a while loop in GDScript, like so:

var ix = 0
var iy = 0
while ix < nx || iy < ny:
    if ((0.5+ix) / nx < (0.5+iy) / ny):
        # next step is horizontal
        p.x += sign_x
        ix += 1
    else:
        # next step is vertical
        p.y += sign_y
        iy += 1
answered Nov 5, 2018 by woopdeedoo (181 points)
selected Nov 5, 2018 by pospathos
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.