anonymous-dev
anonymous-dev

Reputation: 3489

Rotate camera based on mouse postitions around a object Unity3D

Okay, So I have come this far:

public class CameraScript : MonoBehaviour {

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);
    }

}

My camera has a parent which I rotate based on my mouse position. The only problem is that I can only swipe with the mouse to rotate the object. How can I rotate the object which is my camera is attached to based on my mouse position if I just click next to the object. Thanks in advance!

Upvotes: 1

Views: 6726

Answers (1)

Barış Çırıka
Barış Çırıka

Reputation: 1570

The value will be in the range -1...1 for keyboard and joystick input. If the axis is setup to be delta mouse movement, the mouse delta is multiplied by the axis sensitivity and the range is not -1...1. Unity Document

Note: This link is usefull please check it.

So you need to change your code like this.

public void RotateCamera()
{
    Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); // Gets mouse position to Unity World coordinate system
    Camera.mainCamera.transform.parent.transform.Rotate (mousePosition);
}

if there are problem you can do like this

public void RotateCamera()
{
    Vector3 position = new Vector3(Input.mousePosition.x, Input.mousePosition.y,0);
    Vector3 mousePosition = Camera.main.ScreenToWorldPoint(position); // Gets mouse position to Unity World coordinate system
    Camera.mainCamera.transform.parent.transform.Rotate (mousePosition);
}

one more option is rotateTowards.

public float speed=10; //any value > 0
public void RotateCamera()
{
    Vector3 targetDir = Camera.main.ScreenToWorldPoint(Input.mousePosition) - Camera.mainCamera.transform.parent.transform.position;
    float step = speed * Time.deltaTime;
    Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0F);
    Camera.mainCamera.transform.parent.transform.rotation =  Quaternion.LookRotation(newDir);
}

Maybe some syntax errors, i don't check them.

Upvotes: 2

Related Questions