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

Clamping Rotation In Unity2D

Discussion in '2D' started by Thunderline-Studios, Mar 1, 2020.

  1. Thunderline-Studios

    Thunderline-Studios

    Joined:
    Jul 27, 2019
    Posts:
    4
    I'm currently working on a rocket ship script, and I want it to clamp rotation. It's also following my mouse and moving towards it on the X-axis. It is constantly moving up on the Y-axis. I've been confused with this issue for a while now. Here is my code:

    Code (CSharp):
    1. void FaceMouse()
    2.     {
    3.         Quaternion rotation = transform.rotation; //Right here is the beginning of the attempt to add a clamp.
    4.  
    5.         if (rotation.z > 180)
    6.         {
    7.             rotation.z = rotation.z = 360;
    8.         }
    9.  
    10.         rotation.z = Mathf.Clamp(rotation.z, -40f, 40f);
    11.         transform.rotation = rotation; // This is the end.
    12.  
    13.         Vector3 mousePosition = Input.mousePosition;
    14.         mousePosition = camera.ScreenToWorldPoint(mousePosition);
    15.  
    16.         directionX = (mousePosition - transform.position).normalized;
    17.         directionY = transform.position.normalized;
    18.  
    19.         transform.up = directionX;
    20.     }
     
  2. manoque

    manoque

    Joined:
    Feb 9, 2020
    Posts:
    5
    From my limited skills, it seems your rocket will never pass the 40 angle. If you want it to keep rotating, you need to get the current rotation and add the mathf.clamp - Meaning you will add rotation... but clamp it at 40 per rotation call. Like I said, I don't see the add to existing rotation here thus why it keeps going up.
     
  3. Thunderline-Studios

    Thunderline-Studios

    Joined:
    Jul 27, 2019
    Posts:
    4
    Oh you read it wrong. I want it to keep going up, but the way I’m clamping it won’t actually clamp it. I’m trying to clamp the rotation. But... what you said about clamping per rotation call makes me want to put it in Update instead. I will test this tomorrow. Thanks