Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Question How to make Mathf.Sin always start at the point?

Discussion in 'Scripting' started by Autoface, Aug 5, 2023.

  1. Autoface

    Autoface

    Joined:
    Sep 23, 2013
    Posts:
    112
    Hi, Quick question. How do I make Mathf.Sin always start from the same point?

    So quick explanation of usage:
    I have a 2D character. When the mouse clicks, the characters arm rotates up and down. My current implementation works but the problem is that when the mouse is clicked, the rotation starts at a different point everytime, Where as I would really like it to start at the "mid point", preferably when rotating upwards.

    Here is a snippet of the current implementation:

    Code (CSharp):
    1.  
    2. private void Update()
    3. {
    4.     float swingSpeed = 15f;
    5.     float maxRotation = 60f;
    6.  
    7.     float rot = maxRotation * Mathf.Sin(Time.time * swingSpeed) + Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg + 45f;
    8.  
    9.     weaponArm.transform.rotation = Quaternion.Euler(0f, 0f, rot);
    10. }
    11.  
    Any help would be great. Thanks. :)
     
  2. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    549
    Code (CSharp):
    1.     private void Update()
    2.     {
    3.         float swingSpeed = 15f;
    4.         float maxRotation = 60f;
    5.         float rot = maxRotation * Mathf.Cos(swingTime * swingSpeed) + Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg + 45f;
    6.         weaponArm.transform.rotation = Quaternion.Euler(0f, 0f, rot);
    7.         swingTime+=Time.deltaTime; // reset swingTime to zero when mouse is clicked
    8.     }
     
    Last edited: Aug 5, 2023
    Autoface likes this.
  3. Autoface

    Autoface

    Joined:
    Sep 23, 2013
    Posts:
    112
    Ah wonderful. That did it.

    Thank you!