Discuss and collaborate on GML scripts

You are not logged in.

- Topics: Active | Unanswered

Pages: **1**

**~Dannyboy~****~hoqhuue(|~**- From: Melbourne, Australia
- Registered: 2009-10-02
- Posts: 21
- Website

I don't think you (xot) got enough sleep before writing these ones They (polygon_area and polygon_centroid) both suffer the same three issues.

```
{
var a,i,j,x1,y1,x2,y2;
a = 0;
j = ds_list_size(polygon);
for (i=0; i<j div 2; i+=1) {
x1 = ds_list_find_value(polygon,(2*i) mod j);
y1 = ds_list_find_value(polygon,(2*i+1) mod j);
x2 = ds_list_find_value(polygon,(2*i+2) mod j);
y2 = ds_list_find_value(polygon,(2*i+3) mod j);
a += x1*y2 - x2*y1;
}
return a / 2;
}
```

The first thing I'd like to point out is that "polygon" is never defined, thus the script will just throw an error. Secondly multiplying i by 2 four times (and dividing j once) every cycle just seems like a waste to me, you should really increase it by 2 instead. Finally "i" and "i + 1" should never be greater than j and therefore "modding" them is unnecessary (although nice for symmetry). I have not actually tested these scripts but assuming the originals worked (which assumes you had a local variable named polygon), these should work better

```
// polygon_area
{
var polygon, a, i, j, x1, y1, x2, y2;
polygon = argument0;
a = 0;
j = ds_list_size(polygon);
for (i=0; i<j; i+=2) {
x1 = ds_list_find_value(polygon,i);
y1 = ds_list_find_value(polygon,i+1);
x2 = ds_list_find_value(polygon,(i+2) mod j);
y2 = ds_list_find_value(polygon,(i+3) mod j);
a += x1*y2 - x2*y1;
}
return a / 2;
}
```

```
// polygon_centroid
{
var polygon,ai,atmp,xtmp,ytmp,i,j,x1,y1,x2,y2;
polygon = argument0;
atmp = 0;
xtmp = 0;
ytmp = 0;
global.xCentroid = 0;
global.yCentroid = 0;
j = ds_list_size(polygon);
for (i=0; i<j; i+=2) {
x1 = ds_list_find_value(polygon,i);
y1 = ds_list_find_value(polygon,i+1);
x2 = ds_list_find_value(polygon,(i+2) mod j);
y2 = ds_list_find_value(polygon,(i+3) mod j);
ai = x1*y2 - x2*y1;
atmp += ai;
xtmp += (x2 + x1) * ai;
ytmp += (y2 + y1) * ai;
}
if (atmp != 0) {
global.xCentroid = xtmp / (3 * atmp);
global.yCentroid = ytmp / (3 * atmp);
}
return atmp / 2;
}
```

Offline

**xot****Administrator**- Registered: 2007-08-18
- Posts: 1,201

Wow, yeah, a lot problems. Those are all good fixes (assuming they work). It's unlike me to waste math operations like that, but I consider the general sloppiness of forgetting to declare and set "polygon" my personal trademark.

*Abusing forum power since 1986.*

Offline

Pages: **1**