Moving Camera Around an Object in Unity – Unity By Example

Moving Camera Around an Object in Unity

Rotate the camera around the selected object.

Steps

  • Create script AroundCamera.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using UnityEngine;
 
public class AroundCamera : MonoBehaviour
{
    [SerializeField] private int _lookSpeedMouse;
    [SerializeField] private Transform _target;
 
    private Vector2 _rotation;
    private float _distanceFromTarget = 3.5f;
 
    private void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * _lookSpeedMouse * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * _lookSpeedMouse * Time.deltaTime;
 
        _rotation.y += mouseX;
        _rotation.x -= mouseY;
        _rotation.x = Mathf.Clamp(_rotation.x, -90, 90);
 
        _distanceFromTarget -= Input.mouseScrollDelta.y;
 
        transform.localEulerAngles = new Vector3(_rotation.x, _rotation.y, 0);
        transform.position = _target.position - transform.forward * _distanceFromTarget;
    }
}
  • Add script to Main Camera

Result

Download

0 0 votes
Article Rating
Subscribe
Notify of
guest


0 Comments
Inline Feedbacks
View all comments