今天在做东西的时候,有个需求就是要做一群鱼在一定的范围内进行移动。当时候看到这个懵逼的,后来想想如果想让鱼在一定的范围内进行移动首先进行确定移动的范围,然后鱼在这个范围内应该游到哪里,然后怎样再加一些角度偏转什么的。我做的比较简单。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveToPos : MonoBehaviour {
public Vector3 target; //鱼在范围内进行移动的点
public float speed = 2; //移动的速度
public float angleSpeed = 0.01f; //鱼旋转的速度 因为面向目标点
public bool isRotate = true;//是否旋转到面向目标点
private void Start()
{
//为鱼随机产生一个目标
SetTarget();
}
private void Update()
{
//转向
if (isRotate)
{
Vector3 vec = (target - transform.position);
Quaternion rotate = Quaternion.LookRotation(vec);
transform.localRotation = Quaternion.Slerp(transform.localRotation, rotate, angleSpeed);
if (Vector3.Angle(vec, transform.forward) < 0.1f)
{
isRotate = false;
}
}
Move();
}
void SetTarget()
{
//这里的x,y,z是对鱼在某个范围的限定 可以根