i will try to explain my problem (sorry for my bad English)
simply , there is a cube in the scene when i move my finger in screen the cube rotate in z
so when the rotate greater the 45 and i end the touch the cube z = 90 … if it more than 90 the cube z = 180;
On mobile so I can’t check my code, but it should be something like
Update ()
{
Vector3 Rot= transform.eulerAngles;
float overRotation = Rot.z % 90;// how much its over 0, 90, 180, 270...
int baseRotation = (int)(Rot.z / 90f)*90;
if(overRotation>=45)
{
transform.eulerAngles = new Vector3(transform.eulerAngles.x,transform.eulerAngles.y, baseRotation +90);
}
else
{
transform.eulerAngles = new Vector3(transform.eulerAngles.x,transform.eulerAngles.y, baseRotation);
}
The thing is though, if you do this in update, you are not allowing the object to rotate at all. As soon as you turn it 1 degree, it gets snapped to 0 degrees.
You should keep track of rotation in another variable, apply that rotation to the object and then snap it with this code. Or at least run this only when the touch is released
You might save the rotation of the object at the begin of the action, and on Update() check the current rotation comparing it with the initial one.
In the code below you’ll not find the logic for the rotation or the input because I only correct your code.
I hope I was helpful.
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour
{
public float begin; //the starting rotation.z
public float current; //the current rotation.z
public float angleForSnap = 45f; //the angle that we want compare
bool isInTouch;
void Start()
{
isInTouch = false;
}
void Update ()
{
if(isInTouch)
{
//update the current rotation.z
current = this.transform.rotation.eulerAngles.z;
//calculate the delta angle between start and current
float currentAngle = current - begin;
//check if is more than 45° and less than 180°
if(currentAngle > angleForSnap && currentAngle < 180f)
{
//rotate counterclockwise
UpdateRotation(-2*angleForSnap);
EndTouch();
}
//check if is less than 315° and more than 0°
else if(currentAngle < 360f - angleForSnap && currentAngle > 0f)
{
//rotate clockwise
UpdateRotation(2*angleForSnap);
EndTouch();
}
}
}
//the function to launch when the finger hit the object
public void BeginTouch()
{
begin = this.transform.rotation.eulerAngles.z;
isInTouch = true;
}
//the function to launch when the finger leave the screen
public void EndTouch()
{
isInTouch = false;
}
private void UpdateRotation(float deltaZ)
{
this.transform.rotation = Quaternion.Euler(
this.transform.rotation.x,
this.transform.rotation.y,
begin + deltaZ
);
begin = this.transform.rotation.eulerAngles.z;
}
}