RaycastHitDisplay.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /**
  2. * Copyright(c) Live2D Inc. All rights reserved.
  3. *
  4. * Use of this source code is governed by the Live2D Open Software license
  5. * that can be found at https://www.live2d.com/eula/live2d-open-software-license-agreement_en.html.
  6. */
  7. using UnityEngine;
  8. using Live2D.Cubism.Core;
  9. using Live2D.Cubism.Framework.Raycasting;
  10. namespace Live2D.Cubism.Samples.Raycasting
  11. {
  12. /// <summary>
  13. /// Casts rays against a <see cref="Model"/> and displays results.
  14. /// </summary>
  15. public sealed class RaycastHitDisplay : MonoBehaviour
  16. {
  17. /// <summary>
  18. /// <see cref="CubismModel"/> to cast rays against.
  19. /// </summary>
  20. [SerializeField]
  21. public CubismModel Model;
  22. /// <summary>
  23. /// UI element to display results in.
  24. /// </summary>
  25. [SerializeField]
  26. public UnityEngine.UI.Text ResultsText;
  27. /// <summary>
  28. /// <see cref="CubismRaycaster"/> attached to <see cref="Model"/>.
  29. /// </summary>
  30. private CubismRaycaster Raycaster { get; set; }
  31. /// <summary>
  32. /// Buffer for raycast results.
  33. /// </summary>
  34. private CubismRaycastHit[] Results { get; set; }
  35. /// <summary>
  36. /// Hit test.
  37. /// </summary>
  38. private void DoRaycast()
  39. {
  40. // Cast ray from pointer position.
  41. var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  42. var hitCount = Raycaster.Raycast(ray, Results);
  43. // Return early if nothing was hit.
  44. if (hitCount == 0)
  45. {
  46. ResultsText.text = "0";
  47. return;
  48. }
  49. // Show results.
  50. ResultsText.text = hitCount + "\n";
  51. for (var i = 0; i < hitCount; i++)
  52. {
  53. ResultsText.text += Results[i].Drawable.name + "\n";
  54. }
  55. }
  56. #region Unity Event Handling
  57. /// <summary>
  58. /// Called by Unity. Initializes instance.
  59. /// </summary>
  60. private void Start()
  61. {
  62. Raycaster = Model.GetComponent<CubismRaycaster>();
  63. Results = new CubismRaycastHit[4];
  64. }
  65. /// <summary>
  66. /// Called by Unity. Triggers raycasting.
  67. /// </summary>
  68. private void Update()
  69. {
  70. // Return early in case of no user interaction.
  71. if (!Input.GetMouseButtonDown(0))
  72. {
  73. return;
  74. }
  75. DoRaycast();
  76. }
  77. #endregion
  78. }
  79. }