Zain Bokhari
Zain Bokhari

Reputation: 31

Drag to rotate without regardless of camera position

I am using drag to rotate objects in 2D and my camera is moving constantly which affects the rotation of the objects. I want to rotation to be independent of camera position. What is the simplest way of doing that? It does rotate my circle as the circles are spawned momentarily.

This is my code for rotation:

private float BaseAngle = 0.0f;

void OnMouseDown()
{
    BaseAngle = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg;
    BaseAngle -= Mathf.Atan2(Camera.main. transform.right.y,           Camera.main.transform.right.x) * Mathf.Rad2Deg;
}

void OnMouseDrag()
{
    float ang = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg - BaseAngle;
    float FCR = ang * 2f;

    if (CirclesinScene.Count > 0)
    {
        //I have an array of circles, I want to rotate the first circle only
        CirclesinScene[0].transform.rotation =      Quaternion.AngleAxis(FCR, Vector3.forward);
    }
}

private void Update()
{
    pos = Camera.main.WorldToScreenPoint(Camera.main.transform.position);
    pos = Input.mousePosition - pos;
}

It works fine as long as i keep the mouse click and not let go, but if i let go of mouse click and and click again to try to rotate again the circle, the circle will rotate strangely, sometimes snip to some unexpected angle, sometimes rotate opposite to the direction of drag. Please help! Thanks in advance :)

Upvotes: 0

Views: 196

Answers (1)

derHugo
derHugo

Reputation: 90580

There is no need to use WorldToScreenPoint or the Camera.transform.position at all. The main issue was that you didn't take the original orientation of the CirclesinScene[0] into account.

This should do it

private void OnMouseDown()
{
    BaseAngle = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg - CirclesinScene[0].transform.eulerAngles.z / 2;
}

private void OnMouseDrag()
{
    var ang = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg - BaseAngle;
    var FCR = ang * 2f;

    if (CirclesinScene.Count > 0)
    {
        //I have an array of circles, I want to rotate the first circle only
        CirclesinScene[0].transform.rotation = Quaternion.Euler(0, 0, FCR);
    }
}

private void Update()
{
    pos = Input.mousePosition;
}

enter image description here

Upvotes: 1

Related Questions