/**
* Copyright(c) Live2D Inc. All rights reserved.
*
* Use of this source code is governed by the Live2D Open Software license
* that can be found at https://www.live2d.com/eula/live2d-open-software-license-agreement_en.html.
*/
using UnityEngine;
using Live2D.Cubism.Core;
using Live2D.Cubism.Framework.Raycasting;
namespace Live2D.Cubism.Samples.Raycasting
{
///
/// Casts rays against a and displays results.
///
public sealed class RaycastHitDisplay : MonoBehaviour
{
///
/// to cast rays against.
///
[SerializeField]
public CubismModel Model;
///
/// UI element to display results in.
///
[SerializeField]
public UnityEngine.UI.Text ResultsText;
///
/// attached to .
///
private CubismRaycaster Raycaster { get; set; }
///
/// Buffer for raycast results.
///
private CubismRaycastHit[] Results { get; set; }
///
/// Hit test.
///
private void DoRaycast()
{
// Cast ray from pointer position.
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hitCount = Raycaster.Raycast(ray, Results);
// Return early if nothing was hit.
if (hitCount == 0)
{
ResultsText.text = "0";
return;
}
// Show results.
ResultsText.text = hitCount + "\n";
for (var i = 0; i < hitCount; i++)
{
ResultsText.text += Results[i].Drawable.name + "\n";
}
}
#region Unity Event Handling
///
/// Called by Unity. Initializes instance.
///
private void Start()
{
Raycaster = Model.GetComponent();
Results = new CubismRaycastHit[4];
}
///
/// Called by Unity. Triggers raycasting.
///
private void Update()
{
// Return early in case of no user interaction.
if (!Input.GetMouseButtonDown(0))
{
return;
}
DoRaycast();
}
#endregion
}
}