Here is my code:
myTransform.rotation.eulerAngles = new Vector3(Mathf.Clamp(myTransform.rotation.eulerAngles.x, -80f, 50f),
myTransform.rotation.eulerAngles.y, myTransform.rotation.eulerAngles.z);
This is the error I am getting:
Cannot modify a value type return value of `UnityEngine.Transform.rotation’. Consider storing the value in a temporary variable
Any help is great!
Try this
Vector3 theRotation = myTransform.rotation.eulerAngles;
theRotation = new Vector3(Mathf.Clamp(theRotation.x, -80f, 50f),theRotation.y,theRotation.z);
myTransform.rotation = theRotation;
Please let me know if this works, as I didn’t have time to test it
@Jordan : Transform.rotation is a Quaternion, not a vector3. It wont work.
this should though…
myTransform.rotation = Quaternion.Euler(Mathf.Clamp(myTransform.rotation.eulerAngles.x, -80f, 50f), myTransform.rotation.eulerAngles.y, myTransform.rotation.eulerAngles.z));
Although clamping angles like that wont work. You need to do something a little more special.
I think this should do it…
float x = myTransform.rotation.eulerAngles.x;
if(x > 180)
x-= 360f;
myTransform.rotation = Quaternion.Euler(Mathf.Clamp(x,-80,50), myTransform.rotation.eulerAngles.y, myTransform.rotation.eulerAngles.z));
Eric5h5
September 2, 2013, 3:29pm
4
Trying to read a single axis from eulerAngles generally doesn’t work, since there’s more than one correct way to convert between quaternions and eulerAngles. You should track rotation yourself instead, as demonstrated by the standard MouseLook script.
–Eric
@James , your second block of code mostly works. Thanks, the only problem is that I am trying to achieve an effect like this:
As you can see, the gun follows the mouse. I already have this effect working properly but once the gun has reached its limited rotation point, it rotates to a weird position. Here is a video of how it looks:
And here is the code:
//Make Gun Follow Mouse
Vector3 gunLookPos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, myTransform.position.x - Camera.main.transform.position.x);
gunLookPos = Camera.main.ScreenToWorldPoint(gunLookPos);
myTransform.LookAt(gunLookPos);
//Limit Rotation of The Gun
float x = myTransform.rotation.eulerAngles.x;
if(x > 180f)
x-= 360f;
myTransform.rotation = Quaternion.Euler(Mathf.Clamp(x,-60,60), myTransform.rotation.eulerAngles.y, myTransform.rotation.eulerAngles.z);
//When Mouse Goes to the other side of Player, rotate the Player
if(Input.mousePosition.x > Screen.width/2f)
{
myTransform.rotation = Quaternion.Euler(0f, 180f, 0f);
leftControls = false;
}
if(Input.mousePosition.x < Screen.width/2f)
{
myTransform.rotation = Quaternion.Euler(0f, 0f, 0f);
leftControls = true;
}
Oh, and I forgot to mention that the gun follow script is in a separate script from the Screen.width/2 part.