How to set rotation.y to predefined angles.

Here the character moves towards the point where you click, it successfully does that, but the problem is i want the character’s rotation only to be setup in 0,90,180 and 270 degrees only,so i am trying to setup its value but the player is still uses default rotation.y that is any degree(26.333 for eg).

	void MoveDir(Vector3 position)
	{
		Vector3 dir = position - transform.position;
		Quaternion rotation = Quaternion.LookRotation(dir);
		rotation.x = 0;
		rotation.z = 0;
		rotationcheck = rotation.y;
		if(rotationcheck>45.0f && rotationcheck<=135.0f)
		{
			rotation.y = 90f;
		}
		else if(rotationcheck>135.0f && rotationcheck<=225.0f)
		{
			rotation.y = 180f;
		}
		else if(rotationcheck>225.0f && rotationcheck<=315.0f)
		{
			rotation.y = 270f;
		}
		else if(rotationcheck>315.0f && rotationcheck<=45.0f)
		{
			rotation.y = 0f;
		}
		players.transform.rotation = rotation;
		
		
	}

First, you need to understand that transform.rotation is a Quaternion in which x,y,z are not angles. Please read this answer:

As for your question, you can do it this way:

 Vector3 dir = position - transform.position;
 float angle = Mathf.Atan2(dir.x, dir.z) * Mathf.Rad2Deg;
 angle = Mathf.Round (angle / 90.0f) * 90.0f;
 transform.rotation = Quaternion.AngleAxis (angle, Vector3.up);

Quaternions contain values between 0 and 1, therefore, if you set 90, 180, 270 or 0 in them directly, it’ll go all drunk on you.

Instead, use EulerAngles for setting absolute values:

// Store Transform as a variable instead of calling the hidden GetComponent :)
Transform m_Transform;

void Start()
{
    // Fill m_Transform
    m_Transform = transform;
}

private void SnappedLookAt(Vector3 targetPos)
{
    // Simple LookAt usage, remove unwanted axici if wished for
    m_Transform.LookAt(targetPos); 

    // Easy way to snap to a value, divide it so you get a number between 0 and 4, 
    // round that, then multiply by 90 resulting in 0, 90, 180, 270 or 360. :)
    float snappedValue = Mathf.RoundToInt(m_Transform.rotation.eulerAngles.y / 90) * 90;

    // Now set the rotation (x and z unchanged, y snapped)
    m_Transform.rotation = Quaternion.Euler(
        new Vector3(
            m_Transform.rotation.eulerAngles.x,
            snappedValue,
            m_Transform.rotation.eulerAngles.z));
}

That should do the trick.
I hope that helps, if you have anymore questions, feel free to ask, if this answer was satisfying enough, please accept it and move onwards with your epic game programming journeys! :smiley:

Yours truly,
~ThePersister :slight_smile: