get angle, and set angle of a game object

I’m trying to get the Y degrees of a game object and then if it’s within certain ranges just snap it to a certain range.

For example, if it’s > 55 degrees and < 65 degrees, I want to just snap it to 60 degrees. How can I do this in C#?

I’m playing around with ToAngleAxis() and Quaternion.AngleAxis() but can’t seem to get them to work.

check this too, it may help: Unity - Scripting API: Quaternion.eulerAngles

I’m not sure, but i’m too tired to try it out :slight_smile:

edit:

using UnityEngine;

public class segitseg : MonoBehaviour {
	void Update () {
		if (transform.rotation.eulerAngles.y>55&transform.rotation.eulerAngles.y<65){
			Quaternion rot=new Quaternion();
			rot.eulerAngles = new Vector3(0, 60, 0);
			transform.rotation=rot;
		}
	}
}
2 Likes

Perfect, thanks!

I’m having issues when I rotate to the left. When rotating to the right it works, but sometimes when rotation to the left it gets kind of messed up. I must be missing something with this logic.

Vector3 rot = selectedObj.transform.rotation.eulerAngles;
		float y = 0f;
		
		if(rot.y > 55  rot.y < 65)
			y = 60;
		if(rot.y > 115  rot.y < 125)
			y = 120;
		if(rot.y > 175  rot.y < 185)
			y = 180;
		if(rot.y > 235  rot.y < 245)
			y = 240;
		if(rot.y > 295  rot.y < 305)
			y = 300;
		if(rot.y > 355  rot.y < 5)
			y = 0;
		
		gObj.transform.rotation = Quaternion.AngleAxis(y, Vector3.up);

i think the problem is because Quaternion.AngleAxis makes it rotate with y around the axis, instead of setting the rotation to y.

use this to set the rotation (maybe there is easyer way, but in c# i found this solution):

Quaternion rot=new Quaternion();
rot.eulerAngles = new Vector3(0, 60, 0);
transform.rotation=rot;

1 Like