Instantly share code, notes, and snippets.

Embed
What would you like to do?
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