Skip to content

Instantly share code, notes, and snippets.

@sebbdk
Last active December 14, 2015 17:59
Show Gist options
  • Select an option

  • Save sebbdk/5126073 to your computer and use it in GitHub Desktop.

Select an option

Save sebbdk/5126073 to your computer and use it in GitHub Desktop.
Get collision point on the normal of a block in a grid
//Calculate intersection point in grid
var V = {x:1, y:-1, z:0, w:1}; //direction
var A = {x:1.5, y:1.5, z:0}; //point or origin
var n = {x:0, y:1, z:0, w:1}; //normal
var b = {x:2, y:0, z:0}; //grid block position
var rp = {x:null, y:null, z:null}; //result position
var mid = (A.x * Math.abs(n.x) + A.y * Math.abs(n.y) + A.z * Math.abs(n.z)) - (b.x * Math.abs(n.x) + b.y * Math.abs(n.y) +b.z * Math.abs(n.z) + n.w);
var rpMagnitude = mid/(V.x * Math.abs(n.x) + V.y * Math.abs(n.y) +V.z * Math.abs(n.z));
rp.x = A.x - V.x * rpMagnitude * 1.00001;
rp.y = A.y - V.y * rpMagnitude * 1.00001;
rp.z = A.z - V.z * rpMagnitude * 1.00001;
//if the rvMagnitude is > than V.w(direction magnitude) than rv is longer than the direction vector
//and then there is no collision on this block normal vector
console.log(rp, rpMagnitude < 0, rpMagnitude);
detected = (rp.x >= b.x && rp.x < b.x+1) && (rp.y >= b.y && rp.y < b.y+1) && (rp.z >= b.z && rp.z < b.z+1)
console.log(detected);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment