Skip to content

Instantly share code, notes, and snippets.

@kitasenjudesign
Created January 13, 2022 04:14
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 kitasenjudesign/6963ee8bbf99a649b9210278760215f8 to your computer and use it in GitHub Desktop.
Save kitasenjudesign/6963ee8bbf99a649b9210278760215f8 to your computer and use it in GitHub Desktop.
Binding on Unity C#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ProceduralModeling;
public class BindTest : MonoBehaviour
{
[SerializeField] private Mesh _mesh;
[SerializeField] SkinnedMeshRenderer _renderer;
private int NUM = 50;
[SerializeField] public Transform[] bones;
private CatmullRomCurve _curve;
[SerializeField] private Vector3 _up;
// Start is called before the first frame update
void Start()
{
//各頂点にウェイトを埋め込む
BoneWeight[] weights = new BoneWeight[_mesh.vertexCount];
var verts = _mesh.vertices;
for(int i=0;i<_mesh.vertexCount;i++){
weights[i].boneIndex0 = Mathf.FloorToInt( (verts[i].z+1f)/2f*(NUM-1) );
// Debug.Log("r" + verts[i].z );
//Debug.Log("weight" + weights[i].boneIndex0);
weights[i].weight0 = 1;//その度合い
}
_mesh.boneWeights = weights;
bones = new Transform[NUM];
Matrix4x4[] bindPoses = new Matrix4x4[NUM];
for(int i=0;i<NUM;i++){
bones[i] = new GameObject("hoge"+i).transform;
//bones[i].parent = i==0 ? transform : bones[i-1];
bones[i].parent = transform;
bones[i].localRotation = Quaternion.identity;
bones[i].localPosition = new Vector3(0,0,(float)i/(float)(NUM-1)-0.5f);
//bindPoses[i] = bones[i].worldToLocalMatrix * bones[i].parent.localToWorldMatrix;
bindPoses[i] = bones[i].worldToLocalMatrix * transform.localToWorldMatrix;
}
_mesh.bindposes = bindPoses;
_renderer.bones = bones;
_renderer.sharedMesh = _mesh;
_curve = new CatmullRomCurve();
_curve.Points.Clear();
for(int i=0;i<NUM;i++){
var p = new Vector3(
5f*Mathf.Sin(3*Time.time + 35f*(float)i/(float)NUM),
5f*Mathf.Cos(3*Time.time + 42f*(float)i/(float)NUM),
5f*Mathf.Sin(3*Time.time + 31f*(float)i/(float)NUM)
);
_curve.Points.Add(p);
}
}
// Update is called once per frame
void Update()
{
var ff = _curve.ComputeFrenetFrames(NUM);
for(int i=0;i<NUM;i++){
bones[i].localPosition = _curve.GetPointAt((float)i/(float)NUM);
bones[i].localRotation = Quaternion.LookRotation(
ff[i].Tangent,
_up
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment