# How create a camera that snaps the yaw to 45 degree increments?

I want to recreate that → YouTube Example

But what I make is that.

I created a C# camera script for my Unity Project which should evaluate between which values in the Y rotation it is and which should slowly snap into place at the next value. My thought, as shown in the script below, is the possibility with an If application or a Case application. I tried to add or subtract the values with “DoWhile” or “while”, but then I find myself in an endless loop.

Example pseudocode:

``````while (_angel != 45)
{
++_angel;
}
``````

Here is my code:

``````public class CameraRotate : MonoBehaviour
{
public Transform target;
int degrees = 10;
void Update()
{
if (Input.GetMouseButton(1))
{
transform.RotateAround(target.position, Vector3.up, Input.GetAxis("Mouse X") * degrees);
}

if (Input.GetMouseButtonUp(1))
{
//I need somethink like Time.deltaTime * the Difference to move closer to the snap value.
float fYRot = Camera.main.transform.eulerAngles.y;
Debug.Log("Target position: " + fYRot);

//45, 135, 225, 315 or snap every +45 degree angle

float _angel = Mathf.Round(fYRot);
Camera.main.transform.rotation = Quaternion.Euler(30, _angel, 0f);
if (_angel >= 0 && _angel <= 90 )
{
Debug.Log("fYRot is = 45: " + Mathf.Round(fYRot));
Camera.main.transform.rotation = Quaternion.Euler(30, 45, 0f);
}
else if (_angel > 90 && _angel <= 180 )
{
Debug.Log("fYRot is = 135: " + Mathf.Round(fYRot));
Camera.main.transform.rotation = Quaternion.Euler(30, 135, 0f);
}
else if (_angel > 180 && _angel <= 270)
{
Debug.Log("fYRot is = 225: " + Mathf.Round(fYRot));
Camera.main.transform.rotation = Quaternion.Euler(30, 225, 0f);
}
else if (_angel > 270 && _angel < 360)
{
Debug.Log("fYRot is = 315: " + Mathf.Round(fYRot));
Camera.main.transform.rotation = Quaternion.Euler(30, 315, 0f);
}
else
{
Debug.Log("fYRot is = < 0 or > 360: " + Mathf.Round(fYRot));
}

/*
* switch or if?!
switch (fYRot)
{
case 45:
//test
break;
case 135:
//test
default:
//test
break;
}
*/
}
}
}
``````

Thanks a lot!!!

You need a different approach. I’ll sketch it out for you; see if you can translate this into code.

• Keep a “targetAngle” property on your camera script. This will always be 45, 135, 225, or 315.
• When the mouse is clicked or a key is pressed or whatever, you will immediately adjust your targetAngle by 90 degrees. If it goes < 0, add 360; if it goes > 360, subtract 360. Log this with Debug.Log (or watch its value in the inspector) to confirm that it is always 45, 135, 225, or 315.
• Also keep a “currentAngle” property on your camera script.
• In your Update method, make currentAngle approach targetAngle using Mathf.MoveTowardsAngle.
• Finally, set your camera rotation using Quaternion.Euler(30, currentAngle, 0).

That should do it!