public int GetNearestInsertionPoint(Vector3 point)
{
point = transform.InverseTransformPoint(point);
// First find which row the click is nearest to:
int rows = GetDisplayLineCount();
// Will tell us where to start searching in our string
int charOffset = 0;
if(rows > 1)
{
float yDiff;
float nearestY = float.PositiveInfinity;
int nearestLine = 1;
for(int i=1; i <= rows; ++i)
{
yDiff = point.y - (GetLineBaseline(rows, i) + BaseHeight * 0.5f);
if(Mathf.Abs(yDiff) < nearestY)
{
nearestY = Mathf.Abs(yDiff);
nearestLine = i;
}
}
// Now find the offset into the string of the
// start of the nearest line:
for (int i = 0, lineCount = 1; i < displayString.Length && lineCount < nearestLine; ++i)
{
if (displayString[i] == '\n')
{
++lineCount;
charOffset = i+1;
}
}
}
int insertionPt = charOffset;
// Now start searching our desired range for the nearest
// character:
for (int i = charOffset; i < displayString.Length && displayString[i] != '\n'; ++i)
{
// Skip whitespace since we can't use its geometry:
if (char.IsWhiteSpace(displayString[i]))
continue;
// Default to after this character:
insertionPt = i+1;
// Keep going until the center of the character is
// to the right of our point:
int idx = i * 4;
float centerX = vertices[idx].x + (0.5f * (vertices[idx + 2].x - vertices[idx].x));
if (centerX >= point.x)
{
insertionPt = i;
break;
}
}
return insertionPt;
}