6
\$\begingroup\$

I'm trying to make a TextMesh appear when ever an enemy prefab is hit.

I currently have this functionality working. However, the text doesn't face the direction the players camera is looking.

At the moment my OnCollisionEnter method contains the following line of code:

GameObject _go = (GameObject)Instantiate(_hitPrefab, collision.gameObject.transform.position, Camera.mainCamera.transform.rotation);

This line happily creates my TextMesh whenever my enemy is hit. I know my issue has something to do with my rotation quaterion, but I have no idea what pass in so it faces my camera. As you can see, I tried setting it Quaterion.Idenitiy thinking it'll show the same way as the enemy it's associated to, but that doesn't work either.

Each time the textmesh appears, its back to front for the player and at a slight angle.

Could someone please help me in getting it so the score always faces the players camera no matter what way he is facing?

\$\endgroup\$

3 Answers 3

6
\$\begingroup\$

You are simply copying the main camera's rotation in your code snippet, try this method:

GameObject _go = (GameObject)Instantiate(_hitPrefab, 
        collision.gameObject.transform.position, Quaternion.identity);
_go.transform.LookAt(Camera.main.transform);

http://docs.unity3d.com/Documentation/ScriptReference/Transform.LookAt.html

You should also have a look into Quaternion.LookRotation.

http://docs.unity3d.com/Documentation/ScriptReference/Quaternion.LookRotation.html

Edit:

This is a very useful community script for camera facing, the results may be slightly better: http://wiki.unity3d.com/index.php?title=CameraFacingBillboard

\$\endgroup\$
2
  • \$\begingroup\$ No problem, I've edited the answer with a link to a very useful script, it may give you slightly better results if you want the TextMesh to be "flat on" facing the camera. \$\endgroup\$ Mar 14, 2013 at 11:35
  • \$\begingroup\$ For anyone wondering, this is called Billboarding and is used when we want a face to "permanently" face the camera, like text in this case. \$\endgroup\$ Jul 26, 2018 at 10:20
1
\$\begingroup\$

May be this will help you out

public Camera m_Camera;

void Update()
{
    transform.LookAt(transform.position + m_Camera.transform.rotation * Vector3.forward,
        m_Camera.transform.rotation * Vector3.up);
}
\$\endgroup\$
0
\$\begingroup\$

This helps me:

Vector3 fwd = _camera.forward;
fwd.y = 0;
transform.rotation = Quaternion.LookRotation(fwd);
\$\endgroup\$
1
  • 1
    \$\begingroup\$ It may be worth noting here that the fwd.y = 0 line will prevent the object from pitching forward/back to align with a camera that's looking upwards or downwards. \$\endgroup\$
    – DMGregory
    Jul 8, 2018 at 16:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .