Get the element with maximum value in a Vector3?

I want a function that will return the array element that represents the maximum value in a Vector3. Here’s what I have right now (meshBounds.size is a Vector3). Can it get better?

// capsuleCollider.direction defaults to 1 (Y-Axis)
if (meshBounds.size.x > meshBounds.size.y)
{
	if (meshBounds.size.z > meshBounds.size.x)
		capsuleCollider.direction = 2;
	else
		capsuleCollider.direction = 0;
}
else if (meshBounds.size.z > meshBounds.size.y)
		capsuleCollider.direction = 2;

You could probably use something like this:

function getMaxElement(v3 : Vector3){
	return Mathf.Max(Mathf.Max(v3.x, v3.y), v3.z);
}
2 Likes

That will get me a float. As you’ll see above, that’s not really what I need.

Sorry. I guess I misunderstood the question.

No problem! :smile: I had that same idea before I realized what I said in my last post.

Here’s the full extent of what I need to do. It works, but I’m sure I’m going about it like an idiot. :roll: Advice appreciated.

if (meshBounds.size.x > meshBounds.size.y)
{
	// capsule is elongated along its local Z axis
	if (meshBounds.size.z > meshBounds.size.x)
	{
		capsuleCollider.radius = (meshBounds.extents.x + meshBounds.extents.y) * .5F;
		capsuleCollider.height = meshBounds.size.z;
		capsuleCollider.direction = 2;
	}
	// capsule is elongated along its local X axis
	else
	{
		capsuleCollider.radius = (meshBounds.extents.y + meshBounds.extents.z) * .5F;
		capsuleCollider.height = meshBounds.size.x;
		capsuleCollider.direction = 0;
	}
}
else if (meshBounds.size.z > meshBounds.size.y)
{
	// capsule is elongated along its local Z axis
	capsuleCollider.radius = (meshBounds.extents.x + meshBounds.extents.y) * .5F;
	capsuleCollider.height = meshBounds.size.z;
	capsuleCollider.direction = 2;
}
// capsule is elongated along its local Y axis
else
{
	capsuleCollider.radius = (meshBounds.extents.x + meshBounds.extents.z) * .5F;
	capsuleCollider.height = meshBounds.size.y;
	// capsuleCollider.direction defaults to 1 (Y-Axis)
}

Vector3 has a [ ] operator defined.

You could do something like this (warning: don’t have Unity here, so completely untested):

float max = -1f, total = 0f;
int axis = 1;
for (int i = 0; i < 3; i++)
{
    if (meshBounds.size[i] > max)
    {
        axis = i;
        max = meshBounds.size[i];
    }
    total += meshBounds.extents[i];
}

capsuleCollider.radius = (total - meshBounds.extents[axis]) * .5F;
capsuleCollider.height = meshBounds.size[axis];
capsuleCollider.direction = axis;

Thanks, tomvds! I figured that would work perfectly, from just reading it, and it has worked a couple times already in practice. Nice work!

There’s no need to explicitly put an f after the integers that are stored into float variables, though.

I forced myself always to ‘f’ float constants. With that habit, I can completely avoid running into conversion warnings, without having to think about it ;).

2 Likes