Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by ratchetunity · Jul 24, 2019 at 10:02 AM · rotationrotatesmoothrotatearoundsmoothly

Rotate camera around object smoothly

Hi!

I'm trying to rotate a camera around a gameobject smoothly when I press space key, but my code isn't working. This is my code:

 [SerializeField] float rotationAngle;
 [SerializeField] float rotationSpeed;
 private Transform cubePosition;
 private float destinationPos;

 private void Start () {
     cubePosition = GameObject.Find("Cube").transform;
     DestinationPosition();
 }

 private void Update()
 {
     SpaceKeyPressed();
 }

 private void SpaceKeyPressed ()
 {
     if (Input.GetKeyDown(KeyCode.Space))
     {
         transform.RotateAround(cubePosition, Vector3.up, Mathf.LerpAngle(transform.eulerAngles.y, destinationPos, rotationSpeed * Time.deltaTime));
     }

 private void DestinationPosition ()
 {
     destinationPos = transform.eulerAngles.y + rotationAngle;
 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by GlassesGuy · Jul 24, 2019 at 10:43 PM

In my games I use an empty gameobject that goes to the target's position and make the camera a child of the placeholder target and rotate the placeholder target with transform.Rotate()

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by $$anonymous$$ · Nov 12, 2021 at 03:26 AM

You could try this. First, you should add this script to your main camera, then just drag the GameObject to the target slot of this script component. You could use your mouse scroll wheel to change camera FOV to get closer or farther of the target

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEditor;
 public class CameraController : MonoBehaviour
 {
     //the center of the camera rotate sphere
     public Transform target;
     public Camera sceneCamera;
 
     [Range(5f, 15f)]
     [Tooltip("How sensitive the mouse drag to camera rotation")]
     public float mouseRotateSpeed = 5f;
 
     [Range(10f, 50f)]
     [Tooltip("How sensitive the touch drag to camera rotation")]
     public float touchRotateSpeed = 10f;
 
     [Tooltip("Smaller positive value means smoother rotation, 1 means no smooth apply")]
     public float slerpSmoothValue = 0.3f;
     [Tooltip("How long the smoothDamp of the mouse scroll takes")]
     public float scrollSmoothTime = 0.12f;
     public float editorFOVSensitivity = 5f;
     public float touchFOVSensitivity = 5f;
 
     //Can we rotate camera, which means we are not blocking the view
     private bool canRotate = true;
 
     private Vector2 swipeDirection; //swipe delta vector2
     private Vector2 touch1OldPos;
     private Vector2 touch2OldPos;
     private Vector2 touch1CurrentPos;
     private Vector2 touch2CurrentPos;
     private Quaternion currentRot; // store the quaternion after the slerp operation
     private Quaternion targetRot;
     private Touch touch;
 
     //Mouse rotation related
     private float rotX; // around x
     private float rotY; // around y
     //Mouse Scroll
     private float cameraFieldOfView;
     private float cameraFOVDamp; //Damped value
     private float fovChangeVelocity = 0;
 
     private float distanceBetweenCameraAndTarget;
     //Clamp Value
     private float minXRotAngle = -85; //min angle around x axis
     private float maxXRotAngle = 85; // max angle around x axis
 
     private float minCameraFieldOfView = 6;
     private float maxCameraFieldOfView = 30;
 
     Vector3 dir;
     private void Awake()
     {
         GetCameraReference();
 
     }
     // Start is called before the first frame update
     void Start()
     {
         distanceBetweenCameraAndTarget = Vector3.Distance(sceneCamera.transform.position, target.position);
         dir = new Vector3(0, 0, distanceBetweenCameraAndTarget);//assign value to the distance between the maincamera and the target
         sceneCamera.transform.position = target.position + dir; //Initialize camera position
 
         cameraFOVDamp = sceneCamera.fieldOfView;
         cameraFieldOfView = sceneCamera.fieldOfView;
     }
 
     // Update is called once per frame
     void Update()
     {
         if (!canRotate)
         {
             return;
         }
         //We are in editor
         if (Application.isEditor || Application.platform == RuntimePlatform.WindowsPlayer)
         {
             EditorCameraInput();
         }
         else //We are in mobile mode
         {
             TouchCameraInput();
         }
 
         if (Input.GetKeyDown(KeyCode.F))
         {
             FrontView();
         }
         if (Input.GetKeyDown(KeyCode.T))
         {
             TopView();
         }
         if (Input.GetKeyDown(KeyCode.L))
         {
             LeftView();
         }
 
     }
 
     private void LateUpdate()
     {
         RotateCamera();
         SetCameraFOV();
     }
 
     public void GetCameraReference()
     {
         if (sceneCamera == null)
         {
             sceneCamera = Camera.main;
         }
 
     }
 
     //May be the problem with Euler angles
     public void TopView()
     {
         rotX = -85;
         rotY = 0;
     }
 
     public void LeftView()
     {
         rotY = 90;
         rotX = 0;
     }
 
     public void FrontView()
     {
         rotX = 0;
         rotY = 0;
     }
 
     private void EditorCameraInput()
     {
         //Camera Rotation
         if (Input.GetMouseButton(0))
         {
             rotX += Input.GetAxis("Mouse Y") * mouseRotateSpeed; // around X
             rotY += Input.GetAxis("Mouse X") * mouseRotateSpeed;
 
             if (rotX < minXRotAngle)
             {
                 rotX = minXRotAngle;
             }
             else if (rotX > maxXRotAngle)
             {
                 rotX = maxXRotAngle;
             }
         }
         //Camera Field Of View
         if (Input.mouseScrollDelta.magnitude > 0)
         {
             cameraFieldOfView += Input.mouseScrollDelta.y * editorFOVSensitivity * -1;//-1 make FOV change natual
         }
     }
 
     private void TouchCameraInput()
     {
         if (Input.touchCount > 0)
         {
             if (Input.touchCount == 1)
             {
                 touch = Input.GetTouch(0);
                 if (touch.phase == TouchPhase.Began)
                 {
                     //Debug.Log("Touch Began");
 
                 }
                 else if (touch.phase == TouchPhase.Moved)  // the problem lies in we are still rotating object even if we move our finger toward another direction
                 {
                     swipeDirection += -touch.deltaPosition * touchRotateSpeed; //-1 make rotate direction natural
                 }
                 else if (touch.phase == TouchPhase.Ended)
                 {
                     //Debug.Log("Touch Ended");
                 }
             }
             else if (Input.touchCount == 2)
             {
                 Touch touch1 = Input.GetTouch(0);
                 Touch touch2 = Input.GetTouch(1);
                 if (touch1.phase == TouchPhase.Began && touch2.phase == TouchPhase.Began)
                 {
 
                     touch1OldPos = touch1.position;
                     touch2OldPos = touch2.position;
 
                 }
                 if (touch1.phase == TouchPhase.Moved && touch2.phase == TouchPhase.Moved)
                 {
                     touch1CurrentPos = touch1.position;
                     touch2CurrentPos = touch2.position;
                     float deltaDistance = Vector2.Distance(touch1CurrentPos, touch2CurrentPos) - Vector2.Distance(touch1OldPos, touch2OldPos);
                     cameraFieldOfView += deltaDistance * -1 * touchFOVSensitivity; // Make rotate direction natual
                     touch1OldPos = touch1CurrentPos;
                     touch2OldPos = touch2CurrentPos;
                 }
 
             }
 
         }
 
         if (swipeDirection.y < minXRotAngle)
         {
             swipeDirection.y = minXRotAngle;
         }
         else if (swipeDirection.y > maxXRotAngle)
         {
             swipeDirection.y = maxXRotAngle;
         }
 
 
     }
 
     private void RotateCamera()
     {
 
         if (Application.isEditor || Application.platform == RuntimePlatform.WindowsPlayer)
         {
             Vector3 tempV = new Vector3(rotX, rotY, 0);
             targetRot = Quaternion.Euler(tempV); //We are setting the rotation around X, Y, Z axis respectively
         }
         else
         {
             targetRot = Quaternion.Euler(-swipeDirection.y, swipeDirection.x, 0);
         }
         //Rotate Camera
         currentRot = Quaternion.Slerp(currentRot, targetRot, Time.smoothDeltaTime * slerpSmoothValue * 50);  //let cameraRot value gradually reach newQ which corresponds to our touch
         //Multiplying a quaternion by a Vector3 is essentially to apply the rotation to the Vector3
         //This case it's like rotate a stick the length of the distance between the camera and the target and then look at the target to rotate the camera.
         sceneCamera.transform.position = target.position + currentRot * dir;
         sceneCamera.transform.LookAt(target.position);
 
     }
 
 
     void SetCameraFOV()
     {
         //Set Camera Field Of View
         //Clamp Camera FOV value
         if (cameraFieldOfView <= minCameraFieldOfView)
         {
             cameraFieldOfView = minCameraFieldOfView;
         }
         else if (cameraFieldOfView >= maxCameraFieldOfView)
         {
             cameraFieldOfView = maxCameraFieldOfView;
         }
 
         cameraFOVDamp = Mathf.SmoothDamp(cameraFOVDamp, cameraFieldOfView, ref fovChangeVelocity, scrollSmoothTime);
         sceneCamera.fieldOfView = cameraFOVDamp;
 
     }
 
 }

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

147 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Snap the rotation of object 2 Answers

How do I rotate an object around another to have its opposite ? 0 Answers

Return camera to start position smoothly 2 Answers

Smooth Camera Rotation relative to World [SOLVED] 1 Answer

Rotate object in the direction where it is going 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges