Unity模拟谐波运动
Unity模拟谐波运动
先上图
上代码, 很简单, 就一个颜色渐变和不同的旋转速度
using UnityEngine;public class Mgr : MonoBehaviour
{const int count = 56;[SerializeField]Transform prefab;Transform[] balls = new Transform[count];Material[] materials = new Material[count];int[] currIndexs = new int[count];Color[] colors = new Color[6] { new Color(1, 0, 0), new Color(1, 1, 0), new Color(0, 1, 0), new Color(0, 1, 1), new Color(0, 0, 1), new Color(1, 0, 1) };float scale = 0;float basicSpeed = 50;float speedDifference = 2;void Start(){for (int i = 0; i < count; i++){Vector3 pos = new Vector3(-3 - i * 0.3f, 0, -i);Transform ball = Instantiate(prefab, pos, Quaternion.identity);Material material = ball.GetComponent<Renderer>().material;balls[i] = ball;materials[i] = material;currIndexs[i] = 0;materials[i].color = colors[0];RefreshScale(i);for (int j = 0; j < i; j++){RefreshColor(j);}}}void Update(){for (int i = 0; i < count; i++){RefreshColor(i);Rotate(i);}if (Input.GetKeyDown(KeyCode.Space)){scale = Random.Range(-0.05f, 0.05f);basicSpeed = Random.Range(-200, 200);speedDifference = Random.Range(-20f, 20f);for (int i = 0; i < count; i++){RefreshScale(i);}}}void RefreshScale(int i){balls[i].localScale = Vector3.one * (1 + i * scale);}void RefreshColor(int i){int currIndex = currIndexs[i];int nextIndex = (currIndex + 1) % 6;Color dir = colors[nextIndex] - colors[currIndex];Color currColor = ColorAdd(materials[i].color, dir * Time.deltaTime);materials[i].color = currColor;if (currColor == colors[nextIndex]){currIndexs[i] = nextIndex;}}Color ColorAdd(Color color1, Color color2){float r = Mathf.Clamp01(color1.r + color2.r);float g = Mathf.Clamp01(color1.g + color2.g);float b = Mathf.Clamp01(color1.b + color2.b);return new Color(r, g, b);}void Rotate(int i){balls[i].RotateAround(Vector3.zero, Vector3.forward, (i * speedDifference + basicSpeed) * Time.deltaTime);}
}
一想到AI可以生成代码, 我还在手敲, 觉得好虚无啊…