Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# with Unity 3D: How do I make a camera move around an object when user moves mouse

I am trying to make a 3d viewing simulation in Unity 4 where the user can select an object and move their mouse to rotate around it (360 degrees) I have taken many shots to try get it to work, but I fail each time, any help will be appreciated and if it is written in C# that would be great! (But it doesn't have to) Thanks in advance!

like image 678
James Avatar asked Dec 06 '22 19:12

James


1 Answers

This is a different and interesting way :) (I use it)

Screenshot

(Here, the cube is the target)

1) Create sphere - Name: "Camera Orbit" - Add material: Transparent (Alpha = 0) - As scale as you want - Rotation: (0,0,0.1f)
2) Add the camera as a "child" to Camera Orbit's surface. Position = (0,"y = camera orbit scale",0) Rotation = (90,0,0)
3) Create empty GameObject - Name: Input Control.

InputControl.cs:

public class InputControl : MonoBehaviour
{
   public GameObject cameraOrbit;

   public float rotateSpeed = 8f;

   void Update()
   {
       if (Input.GetMouseButton(0))
       {
           float h = rotateSpeed * Input.GetAxis("Mouse X");
           float v = rotateSpeed * Input.GetAxis("Mouse Y");

           if (cameraOrbit.transform.eulerAngles.z + v <= 0.1f || cameraOrbit.transform.eulerAngles.z + v >= 179.9f)
                v = 0;

           cameraOrbit.transform.eulerAngles = new Vector3(cameraOrbit.transform.eulerAngles.x, cameraOrbit.transform.eulerAngles.y + h, cameraOrbit.transform.eulerAngles.z + v);
       }

       float scrollFactor = Input.GetAxis("Mouse ScrollWheel");

       if (scrollFactor != 0)
       {
           cameraOrbit.transform.localScale = cameraOrbit.transform.localScale * (1f - scrollFactor);
       }

   }
}

CameraController.cs:

public class CameraController : MonoBehaviour
{
   public Transform cameraOrbit;
   public Transform target;

   void Start()
   {
       cameraOrbit.position = target.position;
   }

   void Update()
   {
       transform.rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y, 0);

       transform.LookAt(target.position);
   }
}

4) Add CameraController.cs to Camera.
5) Add InputControl.cs to Input Control.
6) Set public variables in scripts. ("Camera Orbit" and "Target")

That's all. Mouse click and drag: Rotate - Mouse whell: Zoom in-out.

ps. If you want, you can change target as runtime.

like image 179
sadrag Avatar answered Dec 08 '22 09:12

sadrag