融入动画技术的交互应用
在初始化中先初始化刚体的初速度,给刚体随机方向大小的初速度,在更新函数中,以50fps更新力,其方向始终指向画布中心。
Rigidbody2D rb2d;
public float strength = 1.0f;
Vector3 center;
void Start () {
center = new Vector3(0, 1, 0);
rb2d = GetComponent<Rigidbody2D>();
Vector2 velocity = Random.insideUnitCircle;
rb2d.velocity = velocity;
}
void FixedUpdate () {
Vector3 dir = transform.position-center;
Vector3 Force = -dir.normalized * strength * 10;
rb2d.AddForce(Force);
}
2、 引力2——基于万有引力的画笔实现(给定具有刚体属性的引力中心attractor):
根据万有引力公式F=Gm1m2/(r*r) 实现刚体attractor对笔刷的引力,其方向始终指向attractor。限制了初始速度方向以及距离太小导致引力太大。
void Start()
{ …………
attractor = GameObject.Find(“attractor”);
rb2d = GetComponent();
dir = attractor.transform.position - transform.position;
do{ //限定初始速度的方向
velocity = base_velocity * Random.insideUnitCircle;
dot_value = Vector2.Dot(dir, velocity);
angle = Mathf.Acos(dot_value / (dir.magnitude * velocity.magnitude));
} while (angle < Mathf.PI / 3 && angle > -Mathf.PI / 3);
rb2d.velocity = velocity;
}
void FixedUpdate(){
dir = transform.position - center;
Vector2 dir2d = new Vector2(dir.x, dir.y);
Force = -dir2d.normalized G strength * rb2d.mass * attractor.GetComponent().mass / (distance * distance);
rb2d.AddForce(Force);
…………
}
3、 空气阻力:
根据简易的空气阻力公式F=1/2CS*v^2实现对运动物体的空气阻力,其方向与速度方向相反。
public float C_Drag=1.0f;//阻力系数
Rigidbody2D rb2d;
float S;//面积
void Start () {
S = 1.0f;
Vector2 velocity = Random.insideUnitCircle;
rb2d = GetComponent();
rb2d.velocity = velocity;
}
void FixedUpdate () {
float v = rb2d.velocity.magnitude;
Vector2 Force = -rb2d.velocity.normalized * C_Drag * S * v * v * 0.5f;
rb2d.AddForce(Force);
}
引力1:
引力2:
空气阻力:
Oscillator:在x轴与y轴方向上分别实现简单的简谐振动。
public float x_Amamplitude = 0.01f;
public float y_Amamplitude = 0.01f;
public float x_velocity = 0.5f;
public float y_velocity = 0.5f;
Vector2 aVelocity;
Vector2 angle;
Vector3 location;
void Start () {
aVelocity = new Vector2(Random.Range(-x_velocity, x_velocity), Random.Range(-y_velocity, y_velocity));
angle = new Vector2(0,0);
location = new Vector3(0, 0, 0);
}
void FixedUpdate () {
location.x = x_Amamplitude * Mathf.Sin(angle.x);
location.y = y_Amamplitude * Mathf.Sin(angle.y);
transform.localPosition += location;
angle += aVelocity;
}