- 最后登录
- 2014-10-23
- 注册时间
- 2011-7-19
- 阅读权限
- 90
- 积分
- 81303
- 纳金币
- -1
- 精华
- 11
|
Let's finish Grapher2 by adding a Ripple function, which is a single sine wave emanating from the center of the grid. Here's the entire script.
using UnityEngine;
public class Grapher2 : MonoBehaviour {
public enum FunctionOption {
Linear,
Exponential,
Parabola,
Sine,
Ripple
}
private delegate float FunctionDelegate (Vector3 p, float t);
private static FunctionDelegate[] functionDelegates = {
Linear,
Exponential,
Parabola,
Sine,
Ripple
};
public FunctionOption function;
public int resolution = 10;
private int currentResolution;
private Particle[] points;
private ParticleEmitter emitter;
void Start () {
emitter = GetComponent<articleEmitter>();
CreatePoints();
}
private void CreatePoints () {
if(resolution < 2){
resolution = 2;
}
else if(resolution > 127){
resolution = 127;
}
currentResolution = resolution;
emitter.ClearParticles();
emitter.Emit(resolution * resolution);
points = emitter.particles;
float increment = 1f / (resolution - 1);
int i = 0;
for(int x = 0; x < resolution; x++){
for(int z = 0; z < resolution; z++){
Vector3 p = new Vector3(x * increment, 0f, z * increment);
points.position = p;
points[i++].color = new Color(p.x, 0f, p.z);
}
}
}
void Update () {
if(currentResolution != resolution){
CreatePoints();
}
FunctionDelegate f = functionDelegates[(int)function];
for(int i = 0; i < points.Length; i++){
Vector3 p = points.position;
p.y = f(p, Time.timeSinceLevelLoad);
points.position = p;
Color c = points.color;
c.g = p.y;
points.color = c;
}
emitter.particles = points;
}
private static float Linear (Vector3 p, float t) {
return p.x;
}
private static float Exponential (Vector3 p, float t) {
return p.x * p.x;
}
private static float Parabola (Vector3 p, float t){
p.x = 2f * p.x - 1f;
p.z = 2f * p.z - 1f;
return 1f - p.x * p.x * p.z * p.z;
}
private static float Sine (Vector3 p, float t){
return 0.50f +
0.25f * Mathf.Sin(4 * Mathf.PI * p.x + 4 * t) * Mathf.Sin(2 * Mathf.PI * p.z + t) +
0.10f * Mathf.Cos(3 * Mathf.PI * p.x + 5 * t) * Mathf.Cos(5 * Mathf.PI * p.z + 3 * t) +
0.15f * Mathf.Sin(Mathf.PI * p.x + 0.6f * t);
}
private static float Ripple (Vector3 p, float t){
float squareRadius = (p.x - 0.5f) * (p.x - 0.5f) + (p.z - 0.5f) * (p.z - 0.5f);
return 0.5f + Mathf.Sin(15 * Mathf.PI * squareRadius - 2f * t) / (2f + 100f * squareRadius);
}
} |
|