Which all means we're going to have to write our own script to calculate the center point of a polygon.
First up, let's decide what we mean when we say the 'center' of a polygon. You (might) remember from school plenty of equations for regular polygons, and there's loads to be said about triangles...
But I could recall nothing about finding the center of an irregular polygon, so I was somewhat reassured when I read this:
"Irregular polygons are not considered as having a center, since there is unlikely to be any one point equally distant form each vertex. However, an irregular polygon can have a centroid, or center of gravity."
I checked the equation of a polygon centroid, and then decided it was overkill. What's more, the centroid is not what determines the position of that little blue dot....
1) Find the average position of the vertices:
Here's the simplest and crudest way to find the 'center' of a polygon: add the vertex positions together and then divide by the number of points. For many polygons, this will give you a point somewhere near the center.....
// this script assumes that the first item
// on the selection list is a polyface.
// you need a locator called locator1
// for the last line to work
string $poly = `ls -sl`;
if($poly != "")
string $verts = `polyInfo -fv $poly`;
string $vert = stringToStringArray($verts,
string $obj = `ls -sl -objectsOnly`;
int $numVerts = (`size ($vert)`-2);
for ($i=1; $i< ($numVerts+1); $i++)
string $vertID = ($obj+".vtx["+$vert[$i]+"]");
float $pos = `xform -q -ws -t $vertID`;
$px += $pos;
$py += $pos;
$pz += $pos;
vector $center = <<($px/$numVerts), ($py/$numVerts),
print ("center point of "+$poly+ " is: "+ $center);
xform -os -t ($center.x) ($center.y) ($center.z)
2) Weighted average:
This method uses a weighted average, based on edge length. The return value of this script will give you the location of Maya's little blue polyface selection handle.
This Python script returns an array, which contains the face ID followed by the XYZ positions of the point.
- download the file: getFaceCenters.py
- place it in your user scripts directory
- edit userSetup.mel to include the following:
- python "import getFaceCenters";
This script will iterate through a selection of faces:
In the MEL command line, type:
string $fc = `python "getFaceCenters.faceCenter()"`;
Number of objects in selection: 1
// Result: The center point of face 0 is:
1.06829440594 0.0 1.21612894535 //
float $x = $fc;
setAttr locator1.tx $x;
float $y = $fc;
setAttr locator1.ty $y;
float $z = $fc;
setAttr locator1.tz $z;
Of course, you could always change the data type of the return value to floats; that would make things even easier...