Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving camera around an object in Unity

Tags:

unity3d

Previous posts here did not seem to address my problem.

I'm trying to get my camera to move around a specific point called "target". Target is an empty gameobject set at the center of my game. The idea is that the camera would not move any closer to or farther from target and would simply rotate around the target as though it were moving around an invisible sphere. The camera should always point at target. transform.LookAt(target) does just fine keeping the camera trained on the target, but I cant get the movement correct. Whether I'm moving along the horizontal or vertical axes, it always spirals directly into the target rather than just moving around it. Any ideas?

public class CameraController : MonoBehaviour {

public float speed;
public Transform target;

void Update () {
    transform.LookAt(target);

    if(Input.GetAxis("Vertical") != 0)
    {
        transform.Translate(transform.up * Input.GetAxis("Vertical") * Time.deltaTime * speed); //.up = positive y
    }

    if(Input.GetAxis("Horizontal") != 0)
    {
        transform.Translate(transform.right * Input.GetAxis("Horizontal") * Time.deltaTime * speed); //.right = positive x
    }
}
}
like image 328
Dylan Russell Avatar asked Dec 19 '22 08:12

Dylan Russell


1 Answers

To rotate around a specific point I use Transform.RotateAround:

transform.RotateAround(target.position, transform.right, -Input.GetAxis("Mouse Y") * speed);
transform.RotateAround(target.position, transform.up, -Input.GetAxis("Mouse X") * speed);

Or, if your target moves and you want to keep the same distance between the camera and your target, you can use this piece of code from my answers.unity3d.com page :

public class SphericalCam 
    : MonoBehaviour 
{
     public float MinDist, CurrentDist, MaxDist, TranslateSpeed, AngleH, AngleV;
     public Transform Target;

     public void Update()
     {
         AngleH += Input.GetAxis("Mouse X");
         AngleV -= Input.GetAxis("Mouse Y");
         CurrentDist += Input.GetAxis("Mouse ScrollWheel");
     }

     public void LateUpdate()
     {
         Vector3 tmp;
         tmp.x = (Mathf.Cos(AngleH * (Mathf.PI / 180)) * Mathf.Sin(AngleV * (Mathf.PI / 180)) * CurrentDist + Target.position.x;
         tmp.z = (Mathf.Sin(AngleH * (Mathf.PI / 180)) * Mathf.Sin(AngleV * (Mathf.PI / 180)) * CurrentDist + Target.position.z;
         tmp.y = Mathf.Sin(AngleV * (Mathf.PI / 180)) * CurrentDist + Target.position.y;
         transform.position = Vector3.Slerp(transform.position, tmp, TranslateSpeed * Time.deltaTime);
         transform.LookAt(Target);
     }
 }
like image 162
Mateusz Avatar answered Apr 21 '23 00:04

Mateusz