Skip to content

Instantly share code, notes, and snippets.

@welchi
Created December 11, 2019 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save welchi/0febf8f648a26673ab9f30d1ea23df94 to your computer and use it in GitHub Desktop.
Save welchi/0febf8f648a26673ab9f30d1ea23df94 to your computer and use it in GitHub Desktop.
using UnityEngine;
using Live2D.Cubism.Core;
public class MouthOpenParam : MonoBehaviour
{
[SerializeField] DlibWebCamFaceDetector faceDetector;
[SerializeField] CubismParameter mouthOpenParameterX;
[SerializeField] CubismParameter mouthOpenParameterY;
[SerializeField] float lerpT = 0.2f;
private float _mouthOpenX;
private float _mouthOpenY;
private void LateUpdate()
{
var landmarks = faceDetector.Landmarks;
// 口の開き(X軸)
float distanceOfMouthWidth = new Vector2(landmarks[48].x - landmarks[54].x, landmarks[48].y - landmarks[54].y)
.sqrMagnitude;
float distanceBetweenEyes = new Vector2(landmarks[39].x - landmarks[42].x, landmarks[39].y - landmarks[42].y)
.sqrMagnitude;
// ゼロ除算対策
if (distanceBetweenEyes != 0)
{
float ratio = distanceOfMouthWidth / distanceBetweenEyes;
float currentMouthOpenX = Mathf.InverseLerp(1.8f, 2.0f, ratio);
_mouthOpenX = Mathf.Lerp(_mouthOpenX, currentMouthOpenX, lerpT);
}
// 口の開き(Y軸)
float distanceOfMouthHeight = new Vector2(landmarks[51].x - landmarks[57].x, landmarks[51].y - landmarks[57].y)
.sqrMagnitude;
float distanceOfNoseHeight = new Vector2(landmarks[33].x - (landmarks[39].x + landmarks[42].x) / 2,
landmarks[33].y - (landmarks[39].y + landmarks[42].y) / 2).sqrMagnitude;
// ゼロ除算対策
if (distanceOfNoseHeight != 0)
{
float ratio = distanceOfMouthHeight / distanceOfNoseHeight;
float currentMouthOpenY = Mathf.InverseLerp(0.2f, 0.6f, ratio);
_mouthOpenY = Mathf.Lerp(_mouthOpenY, currentMouthOpenY, lerpT);
}
SetParameter(mouthOpenParameterX, _mouthOpenX);
SetParameter(mouthOpenParameterY, _mouthOpenY);
}
void SetParameter(CubismParameter parameter, float value)
{
if (parameter != null)
{
parameter.Value = Mathf.Clamp(value, parameter.MinimumValue, parameter.MaximumValue);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment