- Home /
How to rotate a camera like Google Earth?
I'm creating a game in Unity3D that contains a planet in a scene. I want the camera to move around the planet and rotate in the vector direction of the mouse when the player is holding down the right click anywhere on the screen. I have code written out as seen below. The code works great, however the player is only able to rotate the camera around the planet if the mouse is on the planet and not off the planet. How do I change it so that the camera will rotate around the planet even if the mouse is not on the planet?
public class CameraHumanMovement : MonoBehaviour {
[Header("Settings")]
public float planetRadius = 100f;
public float distance;
public GameObject planet;
public Transform camTransform;
public Transform holderTransform;
private Vector3? mouseStartPosition1;
private Vector3? currentMousePosition1;
public bool dog;
private void LateUpdate()
{
if (Input.GetMouseButtonDown(1))
mouseStartPosition = GetMouseHit();
if (mouseStartPosition != null)
DragPlanet();
if (Input.GetMouseButtonUp(1))
StaticPlanet();
}
private void DragPlanet()
{
currentMousePosition1 = GetMouseHit();
RotateCamera((Vector3)mouseStartPosition1, (Vector3)currentMousePosition1);
}
private void StaticPlanet()
{
mouseStartPosition1 = null;
currentMousePosition1 = null;
}
private void RotateCamera(Vector3 dragStartPosition, Vector3 dragEndPosition)
{
//normalised for odd edges
dragEndPosition = dragEndPosition.normalized * planetRadius;
dragStartPosition = dragStartPosition.normalized * planetRadius;
// Cross Product
Vector3 cross = Vector3.Cross(dragEndPosition, dragStartPosition);
// Angle for rotation
float angle = Vector3.SignedAngle(dragEndPosition, dragStartPosition, cross);
//Causes Rotation of angle around the vector from Cross product
holderTransform.RotateAround(planet.transform.position, cross, angle);
}
private static Vector3? GetMouseHit()
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
{
return hit.point;
}
return null;
}
}
You might want concidering targeting mouse move delta in screen space ins$$anonymous$$d of using coords on a mesh ? With the right speed it would give the same result ?
Your answer
Follow this Question
Related Questions
Unity - Dancing Ball World camera following and rotating system 1 Answer
Camera/can't turn on X 1 Answer
Rotate Character Controller Camera 0 Answers
Drag Camera only when raycasting Terrain 1 Answer
Camera Zoom in&out 2 Answers