Hello everyone!
I’m having a problem getting my object to stop rotating at 30 and -30 degrees. It will always continue past them in positive and negative.
Here is my code.
I have found a few topics on here that are similar but nothing has worked so far.
private float h;
private float horozontalSpeed = 0.75f;
private Touch touch;
private bool active;
void Update()
{
if(!active)
{
if (Input.touchCount == 1)
{
touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Moved)
{
h = Mathf.Clamp(horozontalSpeed * touch.deltaPosition.x, -30.0f, 30.0f);
transform.Rotate( 0.0f, -h, 0.0f, Space.World);
print (h);
}
}
}
}
public void StopRotate()
{
print ("Stop rotating, damn you!");
active = !active;
}
}
Please let me know if you need any more information!
Do not use transform.Rotate() it’s using your current object rotation. transform.eulerAngles (Unity - Scripting API: Transform.eulerAngles) should solve your problem.
float rotationY = transform.localEulerAngles.y + h;
float relativeRotationY = (rotationY < 180)? rotationY : - 360 + rotationY;
relativeRotationY = Mathf.Clamp(relativeRotationY, -30, 30);
transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, relativeRotationY,transform.localEulerAngles.z);
But it’s a bad pratice to change rotation with eulerAngles because of potential Gimbal lock.
Instead you should test your current orientation and rotate only when your value is not too high or too low like this :
float min = -30, max = 30;
float relativeRotationY = (transform.localEulerAngles.y < 180)? transform.localEulerAngles.y : - 360 + transform.localEulerAngles.y;
if(h < 0 && relativeRotationY > min ||
h > 0 && relativeRotationY < max)
transform.Rotate( 0.0f, h, 0.0f, Space.World);
if(relativeRotationY < min)
transform.Rotate( 0.0f, -relativeRotationY + min, 0.0f, Space.World);
if(relativeRotationY > max)
transform.Rotate( 0.0f, -relativeRotationY + max, 0.0f, Space.World);