- Home /
How do I clamp the Z-Axis Rotation for this code?
The code below rotates my wheel on the Z-Axis, but it does so in the whole 360 degrees (0 to 360).
I only want it to be able to rotate from 180 to 360.
if (Input.touchCount > 0)
{
for(int i = 0; i < Input.touchCount; i++)
{
ray = Camera.main.ScreenPointToRay(Input.touches[i].position);
if(Input.touches[i].phase == TouchPhase.Began)
{
if(Physics.Raycast(ray, out hit) && hit.collider == this.GetComponent<Collider>())
{
Vector3 wp = Input.GetTouch(i).position;
var dir = Camera.main.WorldToScreenPoint(transform.localPosition);
dir = wp - dir;
baseAngle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
baseAngle -= Mathf.Atan2(transform.right.y, transform.right.x) * Mathf.Rad2Deg;
}
}
if(Input.touches[i].phase == Moved)
{
Vector3 wp = Input.GetTouch(i).position;
var dir = Camera.main.WorldToScreenPoint(transform.localPosition);
dir = wp - dir;
angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - baseAngle;
transform.localRotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
}
Thanks! :)
Answer by fafase · Mar 28, 2015 at 11:58 AM
Lucky you I did one similar thing lately:
public void RotateShip(Vector3 tapPosition)
{
float polarity = (tapPosition.x < halfWidth) ? 1f : -1f;
transform.Rotate(Vector3.forward, polarity * Time.deltaTime * speed);
float angle = transform.eulerAngles.z;
transform.eulerAngles = new Vector3(0f, 0f, ClampAngle(angle, -45f,45f));
}
private float ClampAngle(float angle, float min, float max)
{
if(angle < 90f || angle > 270f)
{
if(angle > 180)
{
angle -= 360f;
}
if(max > 180)
{
max -= 360f;
}
if(min > 180)
{
min -=360f;
}
}
angle = Mathf.Clamp (angle, min, max);
if(angle < 0)
{
angle += 360f;
}
return angle;
}
tapPosition is the screen position of the touch as it was for our project, in your case, I guess it will be the touch position.
The parameters in ClampAngle define the range of rotation, in the example it is from -45 to 45 considering 0 to be the initial rotation.
The ClampAngle method comes from there: http://answers.unity3d.com/questions/141775/limit-local-rotation.html
you would have to change polarity maybe as in my case it was just if the touch was on left or right half of the screen.
And why should he just not put $$anonymous$$athf.Clamp after the line 28 as I said ?
As you said where? The long version allows to use the rotation clamping in all situation, that is whether you need from 0 to 180 or 180 to 360 (which is 0, there is why you cannot just put clamp on line 28) or -45 to 45.