Skip to content

Instantly share code, notes, and snippets.

@williame
Created July 5, 2013 13:12
Show Gist options
  • Save williame/5934448 to your computer and use it in GitHub Desktop.
Save williame/5934448 to your computer and use it in GitHub Desktop.
broken ray cast code
// adapting http://gamedev.stackexchange.com/a/49423/4129
castRay: function(ray) {
var oX = ray[0][0], oY = ray[0][1], oZ = ray[0][2],
dX = ray[1][0]-oX, dY = ray[1][1]-oY, dZ = ray[1][2]-oZ,
x = Math.floor(oX), y = Math.floor(oY), z = Math.floor(oZ),
intbound = function(s,ds) {
if(ds < 0)
return intbound(-s,-ds);
return (1-((s%ds+ds)%ds))/ds;
},
tMaxX = intbound(oX,dX), tMaxY = intbound(oY,dY), tMaxZ = intbound(oZ,dZ),
signum = function(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; },
stepX = signum(dX), stepY = signum(dY),stepZ = signum(dZ),
tDeltaX = stepX/dX, tDeltaY = stepY/dY, tDeltaZ = stepZ/dZ,
fX = 0, fY = 0, fZ = 0, ret, block;
if(dX === 0 && dY === 0 && dZ === 0)
throw new RangeError("Raycast in zero direction!");
while ((stepX > 0? x < dX: x >= dX) &&
(stepY > 0? y < dY: y >= dY) &&
(stepZ > 0? z < dZ: z >= dZ)) {
block = this.getBlock(x,y,z);
if(block) {
if(!ret)
ret = [];
ret.push([[x,y,z],block,[fX,fY,fZ]]);
}
if(tMaxX < tMaxY) {
if(tMaxX < tMaxZ) {
x += stepX;
tMaxX += tDeltaX;
fX = -stepX; fY = 0; fZ = 0;
} else {
z += stepZ;
tMaxZ += tDeltaZ;
fX = 0; fY = 0; fZ = -stepZ;
}
} else {
if(tMaxY < tMaxZ) {
y += stepY;
tMaxY += tDeltaY;
fX = 0; fY = -stepY; fZ = 0;
} else {
z += stepZ;
tMaxZ += tDeltaZ;
fX = 0; fY = 0; fZ = -stepZ;
}
}
}
return ret;
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment