en造数据结构与算法C# 群组行为优化 和 头鸟控制
实现:
1.给鸟类随机播放随机动画使得每一只鸟扇翅膀的频率都不尽相同
2.可以自行添加权重,并在最后 sumForce = separationForce + cohesionForce + alignmentForce;分别乘上相应权重,这样鸟就能快速飞行和转向辣
using System.Collections.Generic;
using UnityEngine;
using System.Collections;
public class BoidsCode1 : MonoBehaviour {
Rigidbody rb;
//鸟群存储线性表
public List<GameObject> birdNeighbors = new List<GameObject>();
//separation分离 alignment对齐 cohesion凝聚
public Vector3 separationForce = Vector3.zero;
public Vector3 alignmentForce = Vector3.zero;
public Vector3 cohesionForce = Vector3.zero;
//平均位置,鸟群朝向
public Vector3 averagePosition = Vector3.zero;
public Vector3 birdForward = Vector3.zero;
//鸟群速度
public Vector3 birdVelocity = Vector3.zero;
//总力
public Vector3 sumForce;
//检测间隔
public float checkInterval = 0.2f;
//检测距离
public float checkDistance = 2;
//分离力最大值
public float maxSeparationForce = 1.0f;
private void Awake() {
rb = GetComponent<Rigidbody>();
}
private void Start() {
InvokeRepeating("CalcForce", 0, checkInterval);
}
//计算函数
private void CalcForce() {
//清空邻居鸟的列表
birdNeighbors.Clear();
//检测到范围内所有的鸟
Collider[] colliders = Physics.OverlapSphere(transform.position, checkDistance);
foreach (Collider collider in colliders) {
if (collider != null && collider.gameObject != this.gameObject) {
//添加到列表里面
birdNeighbors.Add(collider.gameObject);
}
}
//平均点位置为0
averagePosition = Vector3.zero;
//朝向设置为0
birdForward = Vector3.zero;
birdVelocity = Vector3.zero;
separationForce = Vector3.zero; //分离力重设
cohesionForce = Vector3.zero; //凝聚力重设
alignmentForce = Vector3.zero; //对齐力重设
foreach (GameObject bird in birdNeighbors) {
//设定分离力的方向
Vector3 spForceDirection = (this.transform.position - bird.transform.position);
if (spForceDirection.magnitude > 0) {
separationForce += spForceDirection.normalized / spForceDirection.sqrMagnitude;
}
//得到鸟群位置(加起来的和)
averagePosition += bird.transform.position;
//得到鸟群的方向和速度
birdForward += bird.transform.forward;
birdVelocity += bird.GetComponent<Rigidbody>().velocity;
}
//限制分离力的最大值
if (separationForce.magnitude > maxSeparationForce) {
separationForce = separationForce.normalized * maxSeparationForce;
}
//计算平均位置
if (birdNeighbors.Count > 0) {
averagePosition /= birdNeighbors.Count;
}
//设定凝聚力的方向
Vector3 cohesionDirection = (averagePosition - transform.position).normalized;
if (cohesionDirection.magnitude > 0) {
cohesionForce += cohesionDirection;
}
//求取平均速度
if (birdNeighbors.Count > 0) {
alignmentForce = birdVelocity / birdNeighbors.Count;
}
施加分离力
//rb.AddForce(separationForce, ForceMode.VelocityChange);
施加凝聚力
//rb.AddForce(cohesionForce, ForceMode.VelocityChange);
施加对齐力
//rb.AddForce(alignmentForce, ForceMode.VelocityChange);
sumForce = separationForce + cohesionForce + alignmentForce;
rb.AddForce(sumForce,ForceMode.Force);
// 仅当当前鸟不是头鸟时,才设置朝向
if (birdForward.magnitude > 0 && !gameObject.CompareTag("Leader")) {
this.transform.forward = birdForward.normalized;
}
给予一只鸟速度平均速度
//if (alignmentForce.magnitude > 0) {
// this.GetComponent<Rigidbody>().velocity = alignmentForce;
//}
}
}