Rotate object around a center object Unity3D

Hi guys I wrote this code to rotate an object around a center object but I am doing somthing wrong could someone explain me what :)? The idea is that it gets the angle between the center object and the mouse position and based on that angle it must rotate the camera around the canter object.

public GameObject player;

void Update()
{
RotateCamera(player);
}

public void RotateCamera(GameObject _center)
{
    float speedMod = 10.0f;
    Vector3 mousePos = camera.WorldToScreenPoint(Input.mousePosition);
    Vector3 centerPos = _center.transform.position;
    Camera.mainCamera.transform.LookAt(centerPos);
    Camera.mainCamera.transform.RotateAround (centerPos,mousePos,20 * Time.deltaTime * speedMod);
}

1 Answer

1

create a new empty gameobject where you want a pivot point. then make your camera parent of the empty object. then just rotate the new empty object!

That should somthing like this right? The parent of the camera is the empty game object. But it still doesnt work. public void RotateCamera() { Vector3 mousePos = Camera.main.WorldToScreenPoint(Input.mousePosition); Vector3 centerPos = Camera.main.WorldToScreenPoint(Camera.mainCamera.transform.parent.transform.position); Vector3 distance = new Vector3(mousePos.x - centerPos.x, mousePos.y - centerPos.y,0); Camera.mainCamera.transform.parent.transform.Rotate(distance * Time.deltaTime); }

–

I tried this wich looks more like it but it still fails haha public void RotateCamera() { Vector3 mousePos = Input.mousePosition; Vector3 centerPos = Camera.mainCamera.transform.parent.transform.position; Vector3 distance = new Vector3(mousePos.x - centerPos.x, mousePos.y - centerPos.y,mousePos.z - centerPos.z); Camera.mainCamera.transform.parent.transform.Rotate(distance.x * Time.deltaTime,distance.y * Time.deltaTime,distance.z * Time.deltaTime); }

–

Okay, this is almost exactly what I want but now I have to swipe it and I want to be able to click and it rotates. Update() { RotateCamera(); } public void RotateCamera() { float x = 5 * -Input.GetAxis("Mouse X"); float y = 5 * Input.GetAxis("Mouse Y"); Camera.mainCamera.transform.parent.transform.Rotate (y,x,0); }

–