Search code examples
c#cameraunity-game-engineunityscript

Rotate cameran around a gameobject in unity3d


I want to rotate camera around an fbx object when a key is being pressed using unity 3d.How it do? I tried some examples but its not working. First i create a game object and add main camera child of it.


Solution

  • public class CameraOrbit : MonoBehaviour
    {
      public Transform target;
      public float speed = 1f;
      private float distance;
      private float currentAngle = 0;
    
      void Start()
      {
          distance = (new Vector3(transform.position.x, 0, transform.position.z)).magnitude;
      }
    
      void Update()
      {
          currentAngle += Input.GetAxis("Horizontal") * speed * Time.deltaTime;
    
          Quaternion q = Quaternion.Euler(0, currentAngle, 0);
          Vector3 direction = q * Vector3.forward;
          transform.position = target.position - direction * distance + new Vector3(0, transform.position.y, 0);
    
          transform.LookAt(target.position);
      }
    }
    

    I dont have access to unity at the moment so i might have messed something up.

    The idea is keep an angle that you change based on input. Create a Quaternion from the angle (the Quaternion say how to rotate a vector to a certain direction), then rotate a Vector to that direction. Starting from the targets position move in that direction a certain distance and then look at the targets position.

    This only implements rotation around the y axis, if you want rotation around the x axis all you need is another angle variable and then change to this Quaternion.Euler(currentAngleX, currentAngleY, 0);