- Home /
Dividing rotation into segments of 45 degrees
Hi there. I'm making this little game that I need this mechanic for. I want characters to rotate in 45 degree intervals so there's 8 total directions a player can be facing and firing. I had a system where they could just turn 360 degrees but that won't work once I'm going to add visuals. I've been puzzling with it for a few days now and I can't think of a decent solution. Sure, I could write something like
//Constantly updating rotation here if (rotation => -22.5 && rotation < 22.5) { rotation = 0; }
but I know it can be more efficient than that, I just can't figure out how. I'm guessing there's probably a way to regulate this using a for statement and an array with all the rotations, but I just can't figure it out. Any help would be greatly appreciated.
Answer by mchts · Mar 05, 2019 at 07:30 PM
Not sure what you want exactly but lets say you want to rotate your character by 45 degrees around its center depending on finger or mouse position. I've posted a simple script here. Just attach this script to your sprite see it in action. You could simply change the direction with replacing Vector3.forward to whatever direction you want to rotate (i assume it must be x). And once and for all unity 2D is actually 3D with no depth (like scale z is always 0). So there is no problem using Vector3 in 2D platform.
Answer by WarmedxMints · Mar 05, 2019 at 04:42 PM
I've recently messed with this in an open source project. You can check out the project here - Git Hub
In the gun behaviour script, you will find this;
//Get current rotation
var newRot = transform.rotation.eulerAngles;
//Snap it to the nearest desired degree on each axis
newRot.x = Mathf.Round(newRot.x / SnapRotationDegrees) * SnapRotationDegrees;
newRot.y = Mathf.Round(newRot.y / SnapRotationDegrees) * SnapRotationDegrees;
newRot.z = Mathf.Round(newRot.z / SnapRotationDegrees) * SnapRotationDegrees;
//Convert it from a Vector3 back into a Qauternion
var rot = Quaternion.Euler(newRot);
//Do what we want with the new rotation
I've been reading through the code but I am having a bit of trouble comprehending everything. But that $$anonymous$$athf.Round function will probably come in handy since it fixes one of the problems I had with an earlier idea. I'ma see if that's gonna work. Also, I forgot to mention it's a 2D game a bit like surviv.io, which might also be why I'm not understanding everything (I've only really done 2D games and I'm really new regardless)
Your answer