Unity move object in orbit of another object based on mouse(drag) position
So what I did is the following. First I check if the mouse is pressed. If so I will get the mouse position and convert it to a position in the world space. I want to ignore the z because I don't want to move it in the z axis. But you could leave the z there if you want to move it in the z axis also.
Afterwards I check the direction from the planet to the mouse position. To keep it in orbit I will use the the fixed distance that is stored in maxDistance.
And finally if I want the object to look at the planet I will use LookAt.
public void Start()
{
maxDistance = Vector3.Distance(planet.position, transform.position);
}
public void Update()
{
if (Input.GetMouseButton(0))
{
var planetPos = planet.position;
var t = transform;
var mousePos = mainCamera.ScreenToWorldPoint(Input.mousePosition);
mousePos = new Vector3(mousePos.x, mousePos.y, planetPos.z);
var dir = (mousePos - planetPos).normalized;
t.position = planetPos + dir * maxDistance;
t.LookAt(planetPos, Vector3.right);
}
}