Unity鱼群动画功能需求:制作鱼群的随机动画,模拟真实鱼群的⾃由游动,如图
视频教程:(需翻墙)
说明:
实现这个功能只需要两个脚本,
第⼀个是将预设鱼随机克隆出指定数量但不同位置的鱼群;
globalFlock.CS
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
i拼音public class globalFlock : MonoBehaviour {
public GameObject fishPrefab;
public static int tankSize = 5; //这个参数很重要,控制鱼群范围
得字开头的成语static int numFish = 10; //控制鱼群数量
public static GameObject[] allFish = new GameObject[numFish];
public static Vector3 goalPos = ;
// U this for initialization
void Start ()
一语不发
{
for (int i = 0; i < numFish; i++)
{
Vector3 pos = new Vector3(Random.Range(-tankSize, tankSize), //这个参数很重要,控制不同鱼群不同的初始位置 Random.Range(-tankSize, tankSize),奥雷音响
Random.Range(-tankSize, tankSize));
allFish[i] = (GameObject)Instantiate(fishPrefab, pos, Quaternion.identity);
}
}
// Update is called once per frame
void Update ()
{
if(Random.Range(0,10000)<50)
{
goalPos= new Vector3(Random.Range(-tankSize, tankSize),
Random.Range(-tankSize, tankSize),
Random.Range(-tankSize, tankSize));
}
}
}
第⼆个脚本是将鱼群随机动起来;
flock.CS
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class flock : MonoBehaviour {
public float speed = 1f;
float rotationSpeed = 2.0f;
网易云歌曲Vector3 averageHeading;
Vector3 averagePosition;
float neighbourDistance = 5.0f;
bool turning = fal;
// U this for initialization
void Start ()
{
speed = Random.Range(0.5f, 1);
}
// Update is called once per frame
void Update ()
{
if (Vector3.Distance(transform.position, ) >= globalFlock.tankSize) {
海底两万里好词200个
turning = true;
}
el
turning = fal;
if (turning)
{
Vector3 direction = - transform.position;
Quaternion.LookRotation(direction),
rotationSpeed * Time.deltaTime);
speed = Random.Range(0.5f, 1);
}
el
{
if (Random.Range(0, 5) < 3)
ApplyRules();
}
transform.Translate(0, 0, Time.deltaTime * speed);
}
void ApplyRules()
{
GameObject[] gos;
gos = globalFlock.allFish;
Vector3 vcentre = ;
Vector3 vavoid = ;
float gSpeed = 0.1f;
Vector3 goalPos = alPos;
float dist;
int groupSize = 0;
foreach (GameObject go in gos)
{
if (go != this.gameObject)
{
dist = Vector3.ansform.position, ansform.position);
if (dist <= neighbourDistance)
{
vcentre += go.transform.position;
groupSize++;
if (dist < 1.0f)
{
vavoid = vavoid + (ansform.position - go.transform.position); }
flock anotherFlock = go.GetComponent<flock>();
gSpeed = gSpeed + anotherFlock.speed;
吃腰果有什么好处}
}
}奥特曼简笔画彩色
if (groupSize > 0)
{
vcentre = vcentre / groupSize + (goalPos - ansform.position); speed = gSpeed / groupSize;
Vector3 direction = (vcentre + vavoid) - transform.position;
if (direction != )
Quaternion.LookRotation(direction),
rotationSpeed * Time.deltaTime);
}
}
}
具体步骤如下:
1.将需要创建鱼群的鱼预设准备好;
2.创建⼀个空物体,命名为:FishManage,将第⼀个脚本加载上去;
然后运⾏,⼀条鱼就变出了很多不同位置的鱼,如图:
3.在鱼的预设上添加第⼆个脚本,如图:
运⾏,这群鱼就可以随机运动了。如图:
如果要在同⼀场景中设置多群鱼的动画就需要改动⼏个参数,
第⼀个脚本⾥的 Vector3 pos;
第⼆个脚本⾥需要替换所有,这个参数是⽤来指定零点为初始点,如果需要偏移相应的位置,就需要⼿动去设置这个值。