Hi, i´m stuck with a problem due to how new i am to unity.
My problem is, I have a world globe with little objects attached to it representing different locations and i want to rotate the globe (y axis) in order that my selected object is at the center of my camera. Only the globe should rotate. And when deselected the globe returns to its original position.
So far, i figured how to toggle selected/deselected, been trying different ways to rotate but can´t figure out how to always center based on wich objecto i clicked on my globe.
Tried with lookat but couldn´t make it rotate smoothly
Any help is greatly appreciated.
Ok, you will ned to use Quaternions for this.
I made some code for you and it is commented so you can understand what is happening.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class worldglobe : MonoBehaviour {
//This transform is your little object attached to the world globe which you want to be facing to the camera, I assume you already have a mechanism to select the object so I just put it inside a variable.
public Transform selectedObject;
//This is the starting rotation of the world globe so we can return to this rotation when we deselect the object.
Quaternion startingRotation;
//This bool will let us know if the object is selected or not
public bool objectIsSelected = false;
private void Start()
{
//We save the starting rotation of the world globe
startingRotation = transform.rotation;
}
private void Update()
{
if(objectIsSelected)
{
SelectObject(selectedObject);
}
else
{
Deselect();
}
}
void SelectObject(Transform selectedObject)
{
//Here we will get the camera position and the object position both relative to the camera position
Vector3 objectPosition = transform.InverseTransformPoint(selectedObject.position);
Vector3 cameraPosition = transform.InverseTransformPoint(Camera.main.transform.position);
//Here we will get the angle of rotation of the camera and the object position both relative to the globe position and in its Y axis.
float objectAngle = Mathf.Atan2(objectPosition.x, objectPosition.z) * Mathf.Rad2Deg;
float cameraAngle = Mathf.Atan2(cameraPosition.x, cameraPosition.z) * Mathf.Rad2Deg;
//And here we apply the rotation to the world globe
transform.rotation = Quaternion.AngleAxis((cameraAngle - objectAngle) * Time.deltaTime, transform.up) * transform.rotation;
}
void Deselect()
{
//Here we apply the rotation back to its original position
float angle = Vector3.Angle(transform.rotation * Vector3.forward, startingRotation * Vector3.forward);
transform.rotation = Quaternion.AngleAxis(angle * Time.deltaTime, transform.up) * transform.rotation;
}
}
I strongly recommend you that if you are going to be working with rotations read some articles about quaternions, it will help you a lot!