Search Unity

Drag to rotate without regardless of camera position

Discussion in '2D' started by zainnn, Sep 11, 2019 at 4:09 AM.

  1. zainnn

    zainnn

    Joined:
    May 6, 2019
    Posts:
    7
    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?

    This is my code for rotation:
    Code (CSharp):
    1. private float BaseAngle = 0.0f;
    2.  
    3. void OnMouseDown()
    4. {
    5.       BaseAngle = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg;
    6.       BaseAngle -= Mathf.Atan2(Camera.main. transform.right.y,           Camera.main.transform.right.x) * Mathf.Rad2Deg;
    7. }
    8.  
    9. void OnMouseDrag()
    10. {
    11.      
    12.         float ang = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg - BaseAngle;
    13.              float FCR = ang * 2f;
    14.            
    15. if (CirclesinScene.Count > 0)
    16. {
    17.      //I have an array of circles, I want to rotate the first circle only
    18.      CirclesinScene[0].transform.rotation =      Quaternion.AngleAxis(FCR, Vector3.forward);
    19. }
    20.  
    21. }
    22.  
    23. private void Update()
    24. {
    25.             pos = Camera.main.WorldToScreenPoint(Camera.main.transform.position);
    26.             pos = Input.mousePosition - pos;
    27. }
    It does rotate my circle as the circles are spawned momentarily. 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 :)