Skip to content

Instantly share code, notes, and snippets.

@neuro-sys
Created May 3, 2011 15:41
Show Gist options
  • Save neuro-sys/953567 to your computer and use it in GitHub Desktop.
Save neuro-sys/953567 to your computer and use it in GitHub Desktop.
Raycaster: finding distance.
inline void ray(int i, float x, float y, float angle, float fisheye)
{ float fx = x - (int)x, fy = y - (int)y;
float xstep, ystep, xdist, ydist, xx, yy, xdistadd, ydistadd;
int xy, yx;
int xdir = (cos(angle)<0 ? 1 : 0), ydir = (sin(angle)<0 ? 1 : 0);
xstep = 1./tan(angle);
xx = x + (ydir ? fy*-xstep : (1-fy)*xstep);
xy = ydir ? (int)y : (int)y+1;
xdist = sqrt((xx-x)*(xx-x) + (xy-y)*(xy-y));
xdistadd = sqrt(xstep*xstep + 1);
ystep = tan(angle);
yx = xdir ? (int)x : (int)x+1;
yy = y + (xdir ? fx*-ystep : (1-fx)*ystep);
ydist = sqrt((yx-x)*(yx-x) + (yy-y)*(yy-y));
ydistadd = sqrt(ystep*ystep + 1);
while (1)
{ if (ydist > xdist)
{ if (xy<0 || xy>=mapy || (int)xx<0 || (int)xx>=mapx) break;
if (map[xy-ydir][(int)xx] != '`')
{ hstretch(i, map[xy-ydir][(int)xx], ydir?1-(xx-(int)xx):xx-(int)xx, fisheye*xdist, xdist);
break;
}
if (ydir) { xx -= xstep; xy--; xdist += xdistadd; }
else { xx += xstep; xy++; xdist += xdistadd; }
}
else
{ if (yx<0 || yx>=mapx || (int)yy<0 || (int)yy>=mapy) break;
if (map[(int)yy][yx-xdir] != '`')
{ hstretch(i, map[(int)yy][yx-xdir], xdir?yy-(int)yy:1-(yy-(int)yy), fisheye*ydist, ydist);
break;
}
if (xdir) { yy -= ystep; yx--; ydist += ydistadd; }
else { yy += ystep; yx++; ydist += ydistadd; }
} } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment