Search Unity

Question 2d Object relative rotation with mouse drag.

Discussion in 'Scripting' started by Miralay1983, May 24, 2020.

  1. Miralay1983

    Miralay1983

    Joined:
    Mar 11, 2019
    Posts:
    7
    Hi guys. First of all sorry for my worse English.

    I try to make rotate a sprite with mouse drag. I can do it. The script is at below. But the problem is when mouse button down the sprite rotates immediately to the mouse position. I want a rotation with relative to mouse position. I dont want to chase mouse position.

    Thanks a lot.
    Code (CSharp):
    1.  
    2. private void Update()
    3.     {
    4.    
    5.  
    6.        
    7.         pos = Camera.main.WorldToScreenPoint(transform.position);
    8.  
    9.         dir = Input.mousePosition - pos;
    10.         angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
    11.  
    12.         if (Input.GetMouseButton(0))
    13.         {
    14.            
    15.            
    16.  
    17.                transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
    18.  
    19.            
    20.  
    21.         }
    22.  
    23.      
    24.     }
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    You would store the position of the mouse when it is first pressed and then calculate the rotation based on how much it has moved while the button is held.
     
  3. Miralay1983

    Miralay1983

    Joined:
    Mar 11, 2019
    Posts:
    7
    I cant do it :(
     
  4. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    What have you tried?