Quantcast
Channel: Answers for "How can I set a limit to my object rotation???(Here's the code)"
Viewing all articles
Browse latest Browse all 6

Answer by Peter G

$
0
0

You can try directly testing EulerAngles, but that will give you issues so you should probably try storing them in your own variables. You could do it using transform.Rotate(), but you would need several conditionals to do all the checks and I don't like how it looks. So this is method is different but should do the same thing.

var velocit : float;

//Change the value of these two fields to control the max angles.
var maxRotX = 90.0;
var maxRotY = 180.0;

private var curRotX : float;
private var curRotY : float;

function Update () {

     //This is all still the same.
     var xtrans = Input.GetAxis("Horizontal") * velocit * Time.deltaTime;
     var ytrans = Input.GetAxis("Vertical")   * velocit * Time.deltaTime;
     var ztrans = Input.GetAxis("Fire1")      * velocit * Time.deltaTime;

     transform.Translate(-ytrans,ztrans,xtrans,Space.World);

     //Set the curRot_ to the curRot_ + the _trans and clamp it between the min and max so we will never be larger than some angle.
     curRotX = Mathf.Clamp(curRotX + xtrans, -maxRotX, maxRotX);
     curRotY = Mathf.Clamp(curRotY + ytrans, -maxRotY, maxRotY);

     transform.rotation = Quaternion.Euler(curRotX, 0, curRotY);
     //This constructs an angle (x, y, z) and assigns it to the rotation.
     //EDIT:
     //And you called it ytrans, but you put it in the z pos so I kept that convention.
}

The problem with reading the euler angles directly is that Unity internally stores rotations as quaternions. When it converts them to euler angles, there are multiple values is can give. For example, 90 degrees is the same as -270 degrees. And Unity occasionally changes the value it gives you.


Viewing all articles
Browse latest Browse all 6

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>