Snap direction to angles + shifting
I currently have this following code which snaps a v3 direction to the specified angles
Vector3 SnapToAngle(Vector3 vector3, float snapAngle, float snapAngleShift) {
float angle = Vector3.Angle (vector3, Vector3.up);
if (angle < snapAngle / 2) // Cannot do cross product
return Vector3.up * vector3.magnitude; // with angles 0 & 180
if (angle > 180 - snapAngle / 2)
return Vector3.down * vector3.magnitude;
float t = Mathf.Round (angle / snapAngle);
float deltaAngle = (t * snapAngle) - angle;
Vector3 axis = Vector3.Cross(Vector3.up, vector3);
Quaternion q = Quaternion.AngleAxis (deltaAngle, axis);
return q * vector3;
}
This was provided by @robertbu in this post. https://answers.unity.com/questions/493006/snap-a-direction-vector.html
Now. What I want to do, is to be able to shift the snap angle in such a way that if I set it to snap on 180 degrees increments, I can rotate the axis in which it snaps. Take a look at the image below.
any suggestions on how I can proceed?
Sorry but it's not quite clear around which axis you actually want to rotate. The original question where the code came from wanted to snap the rotation around the local x axis in 3d space. You drawn a pure 2d diagram with no references. The code of robert allows free rotation around the y axis but snaps the rotation around the local x axis.
Generally to apply a shift you just want to apply your shift rotation before any of the original code and undo that rotation before you return the result. However since the axis of rotation is not fixed in this code we can not apply a relative rotation beforehand since we don't know the axis yet. So if you want for example a 10° shift but the vector point exactly up it's impossible to deter$$anonymous$$e a rotation axis for your shift. In his code he has two special cases for up and down. Though this only works because up and down are actual target snap angles.
Sorry for not being clear enough. The game I'm making is a 2d side scroller platformer that involves shooting. Therefore the rotation and snapping involve the Z axis. I've tried several approaches but I'm not really the best at math. Am I making my self clear?
Your answer
Follow this Question
Related Questions
Unity Snap settings. moving slightlty wrong 1 Answer
NullReferenceException: Object reference not set to an instance of an object 2 Answers
ClampMagnitude while ignoring a direction 0 Answers
How to get a vector 3 to vector 2 - c# 1 Answer
C# How can create a list of floats from different types of structs? 0 Answers