getNormalFromSurfacePoint method

Vector3 getNormalFromSurfacePoint(
  1. Vector3 point,
  2. Vector3 result
)

Returns the normal for a given point on this AABB's surface.

Implementation

Vector3 getNormalFromSurfacePoint(Vector3 point, Vector3 result ) {
	// from https://www.gamedev.net/forums/topic/551816-finding-the-aabb-surface-normal-from-an-intersection-point-on-aabb/
	result.set( 0, 0, 0 );

	double distance;
	double minDistance = double.infinity;

	getCenter( center );
	getSize( size );

	// transform point into local space of AABB
	vector.copy( point ).sub( center );

	// x-axis
	distance = ( size.x - vector.x.abs() ).abs();

	if ( distance < minDistance ) {
		minDistance = distance;
		result.set( 1 * vector.x.sign, 0, 0 );
	}

	// y-axis
	distance = ( size.y - vector.y.abs(  ) ).abs();

	if ( distance < minDistance ) {
		minDistance = distance;
		result.set( 0, 1 * vector.y.sign, 0 );
	}

	// z-axis
	distance = ( size.z - vector.z.abs(  ) ).abs();

	if ( distance < minDistance ) {
		result.set( 0, 0, 1 * vector.z.sign);
	}

	return result;
}