# RotationLimitAngle

Dec 9th, 2018
126
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. using UnityEngine;
2. using System.Collections;
3.
4. namespace RootMotion.FinalIK {
5.
6.     /// <summary>
7.     /// Simple angular rotation limit.
8.     /// </summary>
10.     public class RotationLimitAngle : RotationLimit {
11.
12.         #region Main Interface
13.
14.         /// <summary>
15.         /// The swing limit.
16.         /// </summary>
17.         [Range(0f, 180f)] public float limit = 45;
18.         /// <summary>
19.         /// Limit of twist rotation around the main axis.
20.         /// </summary>
21.         [Range(0f, 180f)] public float twistLimit = 180;
22.
23.         #endregion Main Interface
24.
25.         /*
26.          * Limits the rotation in the local space of this instance's Transform.
27.          * */
28.         protected override Quaternion LimitRotation(Quaternion rotation) {
29.             // Subtracting off-limits swing
30.             Quaternion swing = LimitSwing(rotation);
31.
32.             // Apply twist limits
33.             return LimitTwist(swing, axis, secondaryAxis, twistLimit);
34.         }
35.
36.         /*
37.          * Apply swing limits
38.          * */
39.         private Quaternion LimitSwing(Quaternion rotation) {
40.             if (axis == Vector3.zero) return rotation; // Ignore with zero axes
41.             if (rotation == Quaternion.identity) return rotation; // Assuming initial rotation is in the reachable area
42.             if (limit >= 180) return rotation;
43.
44.             Vector3 swingAxis = rotation * axis;
45.
46.             // Get the limited swing axis
47.             Quaternion swingRotation = Quaternion.FromToRotation(axis, swingAxis);
48.             Quaternion limitedSwingRotation = Quaternion.RotateTowards(Quaternion.identity, swingRotation, limit);
49.
50.             // Rotation from current(illegal) swing rotation to the limited(legal) swing rotation
51.             Quaternion toLimits = Quaternion.FromToRotation(swingAxis, limitedSwingRotation * axis);
52.
53.             // Subtract the illegal rotation
55.         }
56.
57.         // Open the User Manual URL