• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Matthew_Crown · Apr 25, 2013 at 12:27 PM · mathf.clamp

How to limit the rotation of an object

Hello to all guys I am new here because I am new to the world of unity. I write to u because some weeks ago I beginned studing scripts and how they works. I am reading the Unity 3.x Game Developement essential and following the exercises and tutorials.

During one of these, I decided to create a turret that rotate on X axis with a limit on its range of rotation (please see the attached image to have a best idea of what I am writing about).

xrotation

So in order to make my project real in the monodevelop first I create the script to rotate the cannon using uparrow and down arrow, here u are what I did in C#:

 public class cannon : MonoBehaviour {
     
 public float m_RotationSpeed =  15;
     
     void Start () {
     }
     
     void Update () 
     {     
       
     float xcontrol = m_RotationSpeed * Time.deltaTime;        
     float xrot = transform.rotation.eulerAngles.x;          
         
         
     if(Input.GetKey(KeyCode.UpArrow)
     {     
     transform.Rotate(xcontrol,0,0);
     }    


     if(Input.GetKey(KeyCode.DownArrow))
     {
     transform.Rotate(-xcontrol,0,0);
     }
     }
     }

Then I create a variable xrot in order to register the angle of the x axis hoping to use it to limit the range of the rotation with an "if" function, but this way seems to be really wrong after hunderd of attempts.

So, I am now at a blind point (a poor point in effect) because I don'tknow what I need to do in order to realize mi porject.

Searching on the web I found a lot of scripts that use a misterous (misterius for me) function called Mathf.Clamp.

I am a true beginner in scripting but I really want to understand and imporve so I am here to ask for your help.

Could anyone help me please? I need someone that would like to write the script for me and explain the functions and how they works. Please I am a true beginner so use the most simple way to explian because it's easy for me get confused, sorry aboutthat. I prefer C# examples, I have never work using Java.

I know it's a boring issue but for me it's very important.

Thank you for the attention and hope to hear form you soon! Best regards

Matthew

xrotation.jpg (56.7 kB)
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
3
Best Answer

Answer by AlucardJay · Apr 25, 2013 at 12:33 PM

Updated Answer :

This was developed from the standard assets script MouseOrbit.

First the current rotations are stored in Start.

Then the cached value of the y rotation is modified by the inputs.

Then that value is processed by the method ClampAngle. This makes sure the cached value is between -360 and 360. Then that value is clamped between the limit values before being returned.

Then a new rotation is constructed using the cached values as euler angles.

Finally that rotation is given to the gameObjects transform. It is important to note this is in world space. If you want to use local space, use transform.localRotation

Here is the C# version :

 using UnityEngine;
 using System.Collections;
 
 public class ClampingRotation : MonoBehaviour 
 {
     public float ySpeed = 250.0f;
     
     public float yMinLimit = -80f;
     public float yMaxLimit = 80f;
     
     private float x = 0.0f;
     private float y = 0.0f;
     private float z = 0.0f;
     
     void Start() 
     {
         x = transform.eulerAngles.x;
         y = transform.eulerAngles.y;
         z = transform.eulerAngles.z;
     }
     
     void Update() 
     {
         if ( Input.GetKey(KeyCode.UpArrow) )
         {
             y += ySpeed * Time.deltaTime;
         }
         
         if ( Input.GetKey(KeyCode.DownArrow) )
         {
             y -= ySpeed * Time.deltaTime;
         }
         
         y = ClampAngle( y, yMinLimit, yMaxLimit );
         
         Quaternion newRot = Quaternion.Euler( x, y, z );
         
         transform.rotation = newRot;
     }
     
     float ClampAngle( float angle, float min, float max )
     {
         if ( angle < -360 )
             angle += 360;
         if ( angle > 360 )
             angle -= 360;
         
         return Mathf.Clamp( angle, min, max );
     }
 }


And for future readers, here is the uJS version :

 #pragma strict
 
 var ySpeed : float = 250.0;
 
 var yMinLimit : float = -80;
 var yMaxLimit : float = 80;
 
 private var x : float = 0.0;
 private var y : float = 0.0;
 private var z : float = 0.0;
 
 function Start() 
 {
     x = transform.eulerAngles.x;
     y = transform.eulerAngles.y;
     z = transform.eulerAngles.z;
 }
 
 function Update() 
 {
     if ( Input.GetKey(KeyCode.UpArrow) )
     {
         y += ySpeed * Time.deltaTime;
     }
     
     if ( Input.GetKey(KeyCode.DownArrow) )
     {
         y -= ySpeed * Time.deltaTime;
     }
     
     y = ClampAngle( y, yMinLimit, yMaxLimit );
     
     var newRot : Quaternion = Quaternion.Euler( x, y, z );
     
     transform.rotation = newRot;
 }
 
 function ClampAngle( angle : float, min : float, max : float ) : float
 {
     if ( angle < -360 )
         angle += 360;
     if ( angle > 360 )
         angle -= 360;
     
     return Mathf.Clamp( angle, min, max );
 }






=======================================================================================

Original Answer :

Always check the Unity Scripting Reference : http://docs.unity3d.com/Documentation/ScriptReference/Mathf.Clamp.html

There are 2 examples, for floats and for integers.

Description : Clamps value between a minimum value and maximum value, and returns a value

For example :

 float myValue = 10.5;
 float clampedValue = Mathf.Clamp( myValue, 1.5, 3.5 );

Here it is feeding myValue into the Clamp command, with the returned value clamped between a minimum of 1.5 and a maximum of 3.5 . So in this example, clampedValue would be 3.5

If myValue was 2.1, clampedValue would return 2.1

If myValue was 0.9, clampedValue would return 1.5


Always check the Unity Scripting Reference. For examples in C#, find the tab on the right hand side, just above the example code. Where it says Javascript, click on this and a drop-down box appears. Now you can select C# example scripts =]


To learn about rotations, I strongly recommend you check out the examples at UnityGems : http://unitygems.com/quaternions-rotations-part-1-c/


With the Unity Standard assets, there is a script called MouseOrbit. Import this script and have a look : Assets > Import Package > Scripts

just like how they have y min and max limits, you could add x min and max limits, then clamp x to these angles after you have calculated the X rotation.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Matthew_Crown · Apr 26, 2013 at 04:36 PM 0
Share

Thanks a lot man! I have learned a lot reading your answer! really thanks again and, if u came in Italy a day,there is a beer waiting for you! :) Cheers!

matthew

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

13 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

I made a better shader how do i fix[add _Shadow Strength]help???>Sorry that im asking for to much 1 Answer

Help In Making a SphereCast for 3D Tire! Working RayCast Script included! 0 Answers

UnityEngine.Input.GetMouseButton(1)) issue 1 Answer

Load Level Help 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges