对于Unity3d中鱼的游动进行改进
项目来源
这个项目来自于我的同学,对于海洋环境和鱼类游动进行了简单模拟
项目分析
本系统以鱼类游泳和感知仿真为主,结合海洋环境的建模与仿真,基于鱼类行为学,通过Untiy3D、3DS MAX两种三维软件来进行创作,模拟鱼类的游泳动作、感知行为和多样性行为,实现模拟海洋环境和鱼类行为,用虚拟的手段进行海底环境的仿真。可以通过WASD进行镜头的切换和跟随
不足之处
对于鱼类的游动只进行了简单模拟,在游动时较为死板,不符合真实鱼类的游动情况
改进方案
利用动画机控制鱼的骨骼和随机游动的代码来控制鱼的游动
代码清单
flock_whale.cs
/控制鱼的随机游动/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class flock_whale : MonoBehaviour
{
bool turnningaction = false;
private Animator animation;
public float speed = 1f;
float rotationSpeed = 0.08f;
Vector3 averageHeading;
Vector3 averagePosition;
float neighbourDistance = 80.0f;
bool turning = false;
void Start()
{
animation = GetComponent<Animator>();
speed = Random.Range(0.5f, 1);
if (Vector3.Distance(transform.position, globalFlock_whale.goalPos) >= globalFlock.tankSize)
turnningaction = true;
//animation.Play("downleft");
}
void Update()
{
if (Vector3.Distance(transform.position, globalFlock_whale.goalPos) >= globalFlock.tankSize*1.7f)
{
turning = true;
}
else
turning = false;
if (turning)
{
Vector3 direction = globalFlock_whale.goalPos - transform.position;
transform.rotation = Quaternion.Slerp(transform.rotation,
Quaternion.LookRotation(direction),
rotationSpeed * Time.deltaTime);
if (turnningaction)
{
animation.CrossFade("downleft", 0.2f);
//print("1");
turnningaction = false;
}
//print("1");
speed = Random.Range(0.5f, 1);
}
else
{
turnningaction = true;
if (Random.Range(0, 5) < 3)
ApplyRules();
}
//print(Time.deltaTime);
transform.Translate(0, 0, Time.deltaTime*speed*1.2f);
}
void ApplyRules()
{
GameObject[] gos;
gos = globalFlock.allFish;
Vector3 vcentre = globalFlock_whale.goalPos;
Vector3 vavoid = globalFlock_whale.goalPos;
float gSpeed = 0.1f;
Vector3 goalPos = globalFlock.goalPos;
float dist;
int groupSize = 0;
foreach (GameObject go in gos)
{
if (go != this.gameObject)
{
dist = Vector3.Distance(go.transform.position, this.transform.position);
if (dist <= neighbourDistance)
{
vcentre += go.transform.position;
groupSize++;
if (dist < 1.0f)
{
vavoid = vavoid + (this.transform.position - go.transform.position);
}
flock anotherFlock = go.GetComponent<flock>();
gSpeed = gSpeed + anotherFlock.speed;
}
}
}
if (groupSize > 0)
{
vcentre = vcentre / groupSize + (goalPos - this.transform.position);
speed = gSpeed / groupSize;
//print(speed);
Vector3 direction = (vcentre + vavoid) - transform.position;
if (direction != globalFlock_whale.goalPos)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
if (turnningaction)
{
animation.CrossFade("downright", 0.2f);
turnningaction = false;
}
// print("1");
}
}
}
}
心得体会
在改进的过程中,查找了许多资料,对于虚拟现实技术有了更加深入的了解,这一方面有着巨大的发展前景。而且这一次的改动并没有完全解决这个项目的不足之处,只是略微增加了鱼游动时的生动性,与现实中的实际情况还有很大的差距,我将继续学习新的知识,完善这个缺点。