Spherecast.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using UnityEngine;
  2. namespace BehaviorDesigner.Runtime.Tasks.Unity.UnityPhysics
  3. {
  4. [TaskCategory("Unity/Physics")]
  5. [TaskDescription("Casts a sphere against all colliders in the scene. Returns success if a collider was hit.")]
  6. public class SphereCast : Action
  7. {
  8. [Tooltip("Starts the spherecast at the GameObject's position. If null the originPosition will be used")]
  9. public SharedGameObject originGameObject;
  10. [Tooltip("Starts the sherecast at the position. Only used if originGameObject is null")]
  11. public SharedVector3 originPosition;
  12. [Tooltip("The radius of the spherecast")]
  13. public SharedFloat radius;
  14. [Tooltip("The direction of the spherecast")]
  15. public SharedVector3 direction;
  16. [Tooltip("The length of the spherecast. Set to -1 for infinity")]
  17. public SharedFloat distance = -1;
  18. [Tooltip("Selectively ignore colliders")]
  19. public LayerMask layerMask = -1;
  20. [Tooltip("Use world or local space. The direction is in world space if no GameObject is specified")]
  21. public Space space = Space.Self;
  22. [SharedRequired]
  23. [Tooltip("Stores the hit object of the spherecast")]
  24. public SharedGameObject storeHitObject;
  25. [SharedRequired]
  26. [Tooltip("Stores the hit point of the spherecast")]
  27. public SharedVector3 storeHitPoint;
  28. [SharedRequired]
  29. [Tooltip("Stores the hit normal of the spherecast")]
  30. public SharedVector3 storeHitNormal;
  31. [SharedRequired]
  32. [Tooltip("Stores the hit distance of the spherecast")]
  33. public SharedFloat storeHitDistance;
  34. public override TaskStatus OnUpdate()
  35. {
  36. Vector3 position;
  37. Vector3 dir = direction.Value;
  38. if (originGameObject.Value != null) {
  39. position = originGameObject.Value.transform.position;
  40. if (space == Space.Self) {
  41. dir = originGameObject.Value.transform.TransformDirection(direction.Value);
  42. }
  43. } else {
  44. position = originPosition.Value;
  45. }
  46. RaycastHit hit;
  47. if (Physics.SphereCast(position, radius.Value, dir, out hit, distance.Value == -1 ? Mathf.Infinity : distance.Value, layerMask)) {
  48. storeHitObject.Value = hit.collider.gameObject;
  49. storeHitPoint.Value = hit.point;
  50. storeHitNormal.Value = hit.normal;
  51. storeHitDistance.Value = hit.distance;
  52. return TaskStatus.Success;
  53. }
  54. return TaskStatus.Failure;
  55. }
  56. public override void OnReset()
  57. {
  58. originGameObject = null;
  59. originPosition = Vector3.zero;
  60. radius = 0;
  61. direction = Vector3.zero;
  62. distance = -1;
  63. layerMask = -1;
  64. space = Space.Self;
  65. }
  66. }
  67. }