Snap vector direction to nearest axis

I have this case when I need to get my character direction is snapped to the nearest axis. Kinda look like this.

My solution is to find the largest axis absolute value of axis. Then, change the largest one to 1 and the others 2 with 0. Change largest axis sign with its original sign.

Example, we have Vector3(-0.5f, 0.1f, 0). The snapped direction is Vector3(-1,0,0).

Vector3 SnappedToNearestAxis(Vector3 direction){
    float x = Abs(direction.x);
    float y = Abs(direction.y);
    float z = Abs(direction.z);
    if (x > y && x > z){
        return Vector3(Sign(direction.x),0,0);
    } else if (y > x && y > z){
        return Vector3(0,Sign(direction.y),0);
    } else {
        return Vector3(0,0,Sign(direction.z));
    }
}

How to get reflection vector?

Reflection Vector

This is one of the problems I encounter often. It might be useful to put solution here.
If you are in hurry or don’t need any explanation, I’ll just leave solution below.

v2 = v1 – 2(v1.n)n

v1.n is dot product & n must be normalized.

Vector3 ReflectVector(Vector3 inputVector, Vector3 normal) {
    float dn = 2 * inputVector.DotProduct(normal);
    return inputVector - normal * dn;
}
Continue reading How to get reflection vector?