Skip to content

Instantly share code, notes, and snippets.

@vl4dimir
Last active November 6, 2016 21:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vl4dimir/8213140 to your computer and use it in GitHub Desktop.
Save vl4dimir/8213140 to your computer and use it in GitHub Desktop.
The math for interpolating a vector on an arbitrary location inside a vector field.
public Vector3 VectorAt(float x, float y, float z) {
if (x < 0f) x = Mathf.Abs(x);
if (y < 0f) y = Mathf.Abs(y);
if (z < 0f) z = Mathf.Abs(z);
int floorX = Mathf.FloorToInt(x);
float tx = x - floorX;
floorX %= Dimension;
int ceilX = Mathf.CeilToInt(x) % Dimension;
int floorY = Mathf.FloorToInt(y);
float ty = y - floorY;
floorY %= Dimension;
int ceilY = Mathf.CeilToInt(y) % Dimension;
int floorZ = Mathf.FloorToInt(z);
float tz = z - floorZ;
floorZ %= Dimension;
int ceilZ = Mathf.CeilToInt(z) % Dimension;
// gradient is a 3D array of Vector3s
return (tx * ty * tz * gradient[ceilX, ceilY, ceilZ] +
tx * ty * (1 - tz) * gradient[ceilX, ceilY, floorZ] +
tx * (1 - ty) * tz * gradient[ceilX, floorY, ceilZ] +
tx * (1 - ty) * (1 - tz) * gradient[ceilX, floorY, floorZ] +
(1 - tx) * ty * tz * gradient[floorX, ceilY, ceilZ] +
(1 - tx) * ty * (1 - tz) * gradient[floorX, ceilY, floorZ] +
(1 - tx) * (1 - ty) * tz * gradient[floorX, floorY, ceilZ] +
(1 - tx) * (1 - ty) * (1 - tz) * gradient[floorX, floorY, floorZ]).normalized;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment