Skip to content

Instantly share code, notes, and snippets.

@kyptov
Created June 29, 2017 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyptov/9c6b6cfb91cf54062fe5adf34b5f7b2e to your computer and use it in GitHub Desktop.
Save kyptov/9c6b6cfb91cf54062fe5adf34b5f7b2e to your computer and use it in GitHub Desktop.
Useful function to detect one of side direction by two vectors. This for elements with 8 different sprites for each side. Based on scalar product.
function getSide(from, to) {
/*
* For nord returns 0, for east - 2, and so on
* Lot of things simplified
* As max and min scalar product is always opposite, than we need to check only some of scalar product
* For example scalar product for nord:
* var nord = {x: 0, y: 1}
* var d0 = x * nord.x + y * nord.y
* x * 0 + y * 1 = y
* So scalar product for nord d0 = y, in this case d0 is simplified
*/
// Direction vector
var x = to.x - from.x;
var y = to.y - from.y;
var d1, d3, d7;
d1 = (x + y) * 0.71;
if (d1 > y) {
if (x <= d1) {
return 1;
}
d3 = (x - y) * 0.71;
if (d3 <= x) {
return 2;
}
if (-y <= d3) {
return 3;
}
if (-d1 <= -y) {
return 4;
}
} else {
if (d1 === y) {
return 0;
}
d7 = (y - x) * 0.71;
if (d7 <= y) {
return 0;
}
if (-x <= d7) {
return 7;
}
if (-d1 <= -x) {
return 6;
}
if (-y <= -d1) {
return 5
}
d3 = (x - y) * 0.71;
if (d3 <= -y) {
return 4;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment