mirror of
https://github.com/vrm-c/UniVRM.git
synced 2026-09-08 20:08:53 -05:00
add LookAtTargetSwitcher
This commit is contained in:
78
Scripts/LookAt/LookAtTargetSwitcher.cs
Normal file
78
Scripts/LookAt/LookAtTargetSwitcher.cs
Normal file
@@ -0,0 +1,78 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
|
||||
namespace VRM
|
||||
{
|
||||
public class LookAtTargetSwitcher : MonoBehaviour
|
||||
{
|
||||
[SerializeField]
|
||||
List<Transform> m_targets = new List<Transform>();
|
||||
|
||||
[SerializeField, Range(0, 90.0f)]
|
||||
float m_thresholdDegrees = 60.0f;
|
||||
|
||||
[SerializeField]
|
||||
VRMLookAtHead m_lookAtHead;
|
||||
|
||||
[SerializeField]
|
||||
Blinker m_blinker;
|
||||
|
||||
private void Reset()
|
||||
{
|
||||
m_lookAtHead = GameObject.FindObjectOfType<VRMLookAtHead>();
|
||||
m_blinker = GameObject.FindObjectOfType<Blinker>();
|
||||
}
|
||||
|
||||
float CalcScore(Transform target)
|
||||
{
|
||||
return Vector3.Dot(m_lookAtHead.Head.WorldForward, target.position - m_lookAtHead.Head.Transform.position);
|
||||
}
|
||||
|
||||
Transform ChooseTarget()
|
||||
{
|
||||
Transform target = null;
|
||||
float maxScore = 0;
|
||||
var min = System.Math.Cos(m_thresholdDegrees * Mathf.Deg2Rad);
|
||||
foreach (var x in m_targets)
|
||||
{
|
||||
var score = CalcScore(x);
|
||||
if (score > min && score > maxScore)
|
||||
{
|
||||
maxScore = score;
|
||||
target = x;
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
Transform m_lastTarget;
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (m_targets == null || m_targets.Count == 0) return;
|
||||
|
||||
var target = ChooseTarget();
|
||||
if (target != m_lastTarget)
|
||||
{
|
||||
// blink
|
||||
//Debug.Log("request");
|
||||
m_lastTarget = target;
|
||||
m_blinker.Request = true;
|
||||
}
|
||||
|
||||
Vector3 targetPosition;
|
||||
if (target == null)
|
||||
{
|
||||
// forward
|
||||
targetPosition = m_lookAtHead.Head.Transform.position + m_lookAtHead.Head.WorldForward * 20.0f;
|
||||
}
|
||||
else
|
||||
{
|
||||
targetPosition = target.position;
|
||||
}
|
||||
// half move
|
||||
transform.position += (targetPosition - transform.position) * 0.5f;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user