Skip to content

Instantly share code, notes, and snippets.

@chigirits
Created May 27, 2023 08:23
Show Gist options
  • Save chigirits/de542ca8d8a833a1fa34b316005ed4a1 to your computer and use it in GitHub Desktop.
Save chigirits/de542ca8d8a833a1fa34b316005ed4a1 to your computer and use it in GitHub Desktop.
DynamicBoneのForceを毎フレーム更新して風を表現
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
// デモ https://twitter.com/chigiri_vrc/status/1662372505183739904
public class DBWindZone : MonoBehaviour
{
// 最大風速
public float amplitude = 5f;
// 風向き・強さが変化する速度
public float speed = 2f;
// DBのY座標によってタイミングをずらす
public float yGapScale = -1f;
// ノイズを用いるときtrue(falseにすると向きが一定リズムで変化)
public bool useNoise = true;
// 各個のDBの Distance To Object の値で最大風速をスケールするときtrue
public bool multiplyWithDistanceToObject = false;
DynamicBone[] dynamicBones = null;
Vector2 noiseDir;
void Awake()
{
if (dynamicBones != null) return;
var a = Random.value * Mathf.PI * 2f;
noiseDir = new Vector2(Mathf.Cos(a), Mathf.Sin(a));
dynamicBones = SceneManager.GetActiveScene()
.GetRootGameObjects()
.SelectMany(o => o.GetComponentsInChildren<DynamicBone>())
.ToArray();
Debug.Log($"[DBWindZone] {dynamicBones.Length} DBs found");
}
void Update()
{
foreach (var db in dynamicBones)
{
float gravity = 0f;
float t = Time.time * speed + db.transform.position.y * yGapScale;
if (useNoise)
{
var v = noiseDir * t;
var noise = Mathf.PerlinNoise(v.x, v.y) * 2f - 1f;
gravity = noise * amplitude;
}
else
{
gravity = Mathf.Sin(t * Mathf.PI * 2f) * amplitude;
}
db.m_Force.x = multiplyWithDistanceToObject ? db.m_DistanceToObject * gravity : gravity;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment