1

I have a small piece of code to make a sprite (in a 3D world) always face the camera (It has to be in 3D space).

public class CS_CameraFacingBillboard : MonoBehaviour {

    private Camera m_Camera;

    private void Start()
    {
        m_Camera = Camera.main;
    } 

    void Update()
    {
        transform.LookAt(transform.position + m_Camera.transform.rotation * 
Vector3.forward, m_Camera.transform.rotation * Vector3.up); 
    }
}

This code ensures the sprite is always facing the camera, causing it to lean backwards as the camera in above the sprite facing down in a 45 degree agle. When I put a rigidbody on the sprite, the sprite moves on its own towards the direction its leaning. The rigidbody works fine without this code attached.

How can I have a sprite that always faces the camera, and has a rigidbody attached?

1 Answers1

2

It seems you've left the rigidbody as Dynamic, you should set it to Kinematic.

EDIT: After you comments, I checked myself inside Unity, and probably I've recreated the behaviour you described. It happens to me too IF I use a Box Collider on the sprite without locking its rigidbody rotation. So you have three possible solutions:

  • Use a Box Collider and under Constraints of the rigidbody freeze the rotation: enter image description here
  • Use a Sphere Collider (or another one that doesn't behave like the box one, you can check them out in play mode).
  • Split the components over two game object, a parent and a child. The parent will have all the components except the sprite renderer and the camera script, which will be on the child. This option is the most flexible and less restraining. You can have the box collider without freezing rotations, etc.

Another thing, you can avoid the use of the LookAt method, by simply using:

transform.rotation = m_Camera.transform.rotation;

they have the same outcome.

Galandil
  • 4,169
  • 1
  • 13
  • 24
  • Thankyou, this does stop it from moving towards the direction. However now the sprite does not fall if kinematic and gravity is ticked. – Karya Sipahi Mar 22 '18 at 23:31
  • When a rigidbody is set to `kinematic`, it means that the physics simulation is disabled, so that's intended. Do you need it to be simulated? It would beat the purpose of it looking always at the camera. – Galandil Mar 22 '18 at 23:36
  • Yes, so the game has a sprite as the player, and where the camera can be rotated around the arena, hence the need for always facing the camera. However the sprite has to be able to fall off platforms. If this is not possible with simple methods, I can recreate the physics now that it has a rigidbody attached (Thankyou for that). I was just wondering if there was an easier way? – Karya Sipahi Mar 22 '18 at 23:52
  • Thankyou so much, you have really helped. – Karya Sipahi Mar 23 '18 at 21:49