Raycast.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using UnityEngine;
  2. namespace BehaviorDesigner.Runtime.Tasks.Unity.UnityPhysics2D
  3. {
  4. [TaskCategory("Unity/Physics2D")]
  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 SharedVector2 originPosition;
  12. [Tooltip("The direction of the ray")]
  13. public SharedVector2 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 SharedVector2 storeHitPoint;
  26. [SharedRequired]
  27. [Tooltip("Stores the hit normal of the raycast.")]
  28. public SharedVector2 storeHitNormal;
  29. [SharedRequired]
  30. [Tooltip("Stores the hit distance of the raycast.")]
  31. public SharedFloat storeHitDistance;
  32. public override TaskStatus OnUpdate()
  33. {
  34. Vector2 position;
  35. Vector2 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. var hit = Physics2D.Raycast(position, dir, distance.Value == -1 ? Mathf.Infinity : distance.Value, layerMask);
  45. if (hit.collider != null) {
  46. storeHitObject.Value = hit.collider.gameObject;
  47. storeHitPoint.Value = hit.point;
  48. storeHitNormal.Value = hit.normal;
  49. #if !UNITY_4_3
  50. storeHitDistance.Value = hit.distance;
  51. #endif
  52. return TaskStatus.Success;
  53. }
  54. return TaskStatus.Failure;
  55. }
  56. public override void OnReset()
  57. {
  58. originGameObject = null;
  59. originPosition = Vector2.zero;
  60. direction = Vector2.zero;
  61. distance = -1;
  62. layerMask = -1;
  63. space = Space.Self;
  64. }
  65. }
  66. }