Need to display a text at coordinates

Problems building or running the engine, queries about how to use features etc.
slapin
Bronze Sponsor
Bronze Sponsor
Posts: 250
Joined: Fri May 23, 2025 5:04 pm
x 16

Need to display a text at coordinates

Post by slapin »

Hi, all!

I have a point in 3D and when it is visible (in frustum) I want the coordinates to be converted to screen coordinates and text drawn there (centered).
I currently use Dear ImGUI but is it possible to draw just text using it? If not, what else?
So questions are:

  1. How to know if 3d point is in frustum in the most efficient way?
  2. How to convert 3d point coordinates to screen coordinates?
  3. How to display text message centered at coordinates?
rpgplayerrobin
Orc Shaman
Posts: 788
Joined: Wed Mar 18, 2009 3:03 am
x 447

Re: Need to display a text at coordinates

Post by rpgplayerrobin »

You should not test if it is in the frustum first, because that would make the text/UI appear/disappear as soon as the middle point of it enters/exists the frustum.
Instead, you need to calculate the final 2D rectangle of your UI element and then check if it is actually on the screen.

Here is a code that should help you with all this (including to convert a 3D position to a 2D one):

Code: Select all

// Gets the screen coordinates (2D) of a 3D position
bool GetScreenCoordinatesOfPosition(Vector3 position, Camera* camera, Vector2& out2DPosition)
{
	// Check if the position is even in the same direction of the camera by using plane collision
	Plane tmpPlane;
	tmpPlane.redefine( -camera->getDerivedOrientation().zAxis(), camera->getDerivedPosition() );
	if (tmpPlane.getDistance( position ) > 0.0f)
	{
		// Get the position of the projection matrix multiplied by the view matrix multiplied by the position
		Vector3 tmpPosition = camera->getProjectionMatrix() * (camera->getViewMatrix() * position);

	// Get the position in 2D
	float tmpWidth = 0.5f;
	float tmpHeight = 0.5f;
	out2DPosition.x = tmpWidth + (tmpWidth * tmpPosition.x);
	out2DPosition.y = tmpHeight + (tmpHeight * -tmpPosition.y);

	// Return that we succeeded
	return true;
}

// Return that we failed
return true;
}

// Check if the 2D position is valid
Vector2 tmp2DPosition = Vector2::ZERO;
if(GetScreenCoordinatesOfPosition(tmp3DPosition, camera, tmp2DPosition))
{
	// Calculate the final rectangle of the text/UI from the tmp2DPosition and check if it is inside the screen (>0 && <1)
}

I cannot answer how to show it as a text with your UI system though, since I use another one.