Search Unity

rotating a clock hand to mouse click position

Discussion in 'Scripting' started by SavedByZero, Jul 16, 2021.

  1. SavedByZero

    SavedByZero

    Joined:
    May 23, 2013
    Posts:
    124
    So I thought this was straightforward:

    Code (CSharp):
    1.  float angle = Mathf.Atan2(Camera.main.ScreenToWorldPoint(Input.mousePosition).y - clockHandCollider.y, Camera.main.ScreenToWorldPoint(Input.mousePosition).x - clockHandCollider.x);
    2.  
    3. angle = (angle * 180) / Mathf.PI;
    4.  
    5. clockHand.transform.Rotate(new Vector3(clockHand.transform.eulerAngles.x, clockHand.transform.eulerAngles.y, angle));
    But this doesn't work. The clockHand's movements seem schizophrenic. Am I missing some basic step with the arc tangent, or am I getting a coordinate space wrong? I want the clock hand to rotate right up to where the mouse cursor is when I click.

    Also, when I turn off click rotation and test my arc tangent between my mouse click and the clock hand tip (collider), it should always be 0 when I click on or around the hand, right? Instead, the arc tangent seems to change as the hand does its natural tick rotation, even if I follow it with the mouse and keep clicking.
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,648
    I think you want transform.rotation, not transform.Rotate(), as Rotate() will add the rotation to the object's current rotation.
     
  3. SavedByZero

    SavedByZero

    Joined:
    May 23, 2013
    Posts:
    124
    I was initially trying that, but I think I might be going about this the wrong way -- I should probably be taking the clock hand's hub as the origin and calculating the absolute rotation (eulerAngles) instead of trying to offset it from the position of the collider on the tip of the arrow.