Raycast.cs 2.7 KB

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