AimPoser.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using UnityEngine;
  2. using System.Collections;
  3. using RootMotion;
  4. namespace RootMotion.FinalIK {
  5. /// <summary>
  6. /// Aim Poser returns a reference by direction.
  7. /// </summary>
  8. public class AimPoser : MonoBehaviour {
  9. /// <summary>
  10. /// the pose definition
  11. /// </summary>
  12. [System.Serializable]
  13. public class Pose {
  14. public bool visualize = true; // Show the direction and range of this pose in the scene view
  15. public string name; // the reference
  16. public Vector3 direction; // the direction of the pose
  17. public float yaw = 75f; // the yaw range
  18. public float pitch = 45f; // the pitch range
  19. private float angleBuffer;
  20. // Determines whether this Pose is in the specified direction.
  21. public bool IsInDirection(Vector3 d) {
  22. if (direction == Vector3.zero) return false;
  23. if (yaw <= 0 || pitch <= 0) return false;
  24. // Yaw
  25. if (yaw < 180f) {
  26. Vector3 directionYaw = new Vector3(direction.x, 0f, direction.z);
  27. if (directionYaw == Vector3.zero) directionYaw = Vector3.forward;
  28. Vector3 dYaw = new Vector3(d.x, 0f, d.z);
  29. float yawAngle = Vector3.Angle(dYaw, directionYaw);
  30. if (yawAngle > yaw + angleBuffer) return false;
  31. }
  32. // Pitch
  33. if (pitch >= 180f) return true;
  34. float directionPitch = Vector3.Angle(Vector3.up, direction);
  35. float dPitch = Vector3.Angle(Vector3.up, d);
  36. return Mathf.Abs(dPitch - directionPitch) < pitch + angleBuffer;
  37. }
  38. // Sets the angle buffer to prevent immediatelly switching back to the last pose if the angle should change a bit.
  39. public void SetAngleBuffer(float value) {
  40. angleBuffer = value;
  41. }
  42. }
  43. public float angleBuffer = 5f; // The angle buffer
  44. public Pose[] poses = new Pose[0]; // The array of poses.
  45. /// <summary>
  46. /// Gets the pose by direction. GetPose will go through the poses array and return the first pose that has the direction in range.
  47. /// </summary>
  48. public Pose GetPose(Vector3 localDirection) {
  49. if (poses.Length == 0) return null;
  50. for (int i = 0; i < poses.Length - 1; i++) if (poses[i].IsInDirection(localDirection)) return poses[i];
  51. return poses[poses.Length - 1];
  52. }
  53. /// <summary>
  54. /// Sets the pose active, increasing it's angle buffer.
  55. /// </summary>
  56. public void SetPoseActive(Pose pose) {
  57. for (int i = 0; i < poses.Length; i++) {
  58. poses[i].SetAngleBuffer(poses[i] == pose? angleBuffer: 0f);
  59. }
  60. }
  61. }
  62. }