Skip to content

Instantly share code, notes, and snippets.

@MrSimsek
Created February 14, 2021 10:37
Show Gist options
  • Save MrSimsek/8bd504d42b3b19b9b5568713c796014b to your computer and use it in GitHub Desktop.
Save MrSimsek/8bd504d42b3b19b9b5568713c796014b to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveAroundObject : MonoBehaviour
{
[SerializeField]
private float _mouseSensitivity = 3.0f;
private float _rotationY;
private float _rotationX;
[SerializeField]
private Transform _target;
[SerializeField]
private float _distanceFromTarget = 3.0f;
private Vector3 _currentRotation;
private Vector3 _smoothVelocity = Vector3.zero;
[SerializeField]
private float _smoothTime = 0.2f;
[SerializeField]
private Vector2 _rotationXMinMax = new Vector2(-40, 40);
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * _mouseSensitivity;
float mouseY = Input.GetAxis("Mouse Y") * _mouseSensitivity;
_rotationY += mouseX;
_rotationX += mouseY;
// Apply clamping for x rotation
_rotationX = Mathf.Clamp(_rotationX, _rotationXMinMax.x, _rotationXMinMax.y);
Vector3 nextRotation = new Vector3(_rotationX, _rotationY);
// Apply damping between rotation changes
_currentRotation = Vector3.SmoothDamp(_currentRotation, nextRotation, ref _smoothVelocity, _smoothTime);
transform.localEulerAngles = _currentRotation;
// Substract forward vector of the GameObject to point its forward vector to the target
transform.position = _target.position - transform.forward * _distanceFromTarget;
}
}
@Titmf
Copy link

Titmf commented Aug 19, 2022

thx a lot

@JobGamesJG
Copy link

This is my favorite orbit camera method. I added an extra touch by SmoothDamping distance with the scroll wheel.

how did you do that?

@Bxmbed
Copy link

Bxmbed commented Aug 8, 2023

Why wont it let me add this script to my Main Camera

@Dimitri-dev3
Copy link

If the camera is shaking it is most likely because the player has a rigidbody and a character controller attached to it

The player only needs the character controller because it has a built in rigidbody

Remove the rigidbody and any colliders on the player that has the character controller component

and the camera will stop shaking

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment