生成人群
public class playerGenerator : MonoBehaviour
{
public GameObject dudePrefeb;//随机生成两种角色,人物自动生成,但生成泰迪熊需要玩家按Fire键才生成,这里生成都是在同一位置(0,0,0),因为有控制角色运动的脚本使得生成之后移动到其他位置
public GameObject teddyPrefeb;
public int Count;//计数,当前已生成角色的数量
public int maxCount = 30;//控制人群的最大数量
public float timeVal = 1f;//控制角色生成的时间间隔
public float lastTime;//上一次生成角色的时间
// public float time;
// Use this for initialization
void Start()
{
lastTime = Time.time;
}
// Update is called once per frame
void Update()
{
if (Count < maxCount)
{
bool fired = Input.GetButton("Fire1");
if ((Time.time - lastTime) > timeVal)
{
if (!fired)
{
Instantiate(dudePrefeb, Vector3.zero, Quaternion.identity);//在同一位置产生
}
if (fired)
{
Instantiate(teddyPrefeb, Vector3.zero, Quaternion.identity);
}
lastTime = Time.time;
Count++;
}
}
}
}
随机运动
动画控制角色随机运动无非就是控制动画的参数,以决定各个动作动画的播放
1.对于角色的移动:
animator.SetFloat(“Speed”,1,SpeedDampTime,Time.deltaTime);//DampTime为到达该值所需要的时间
2.对于方向的改变:
animator.SetFloat(“Direction”,Vector3.Cross(currentDir,wantedDir).y,DirectionDampTime,Time.deltaTime);
//第二项叉积>0 表示方向向右,动画播放应为RunRight
<0表示方向向左,动画播放应为RunLeft;
=0表示方向不变,动画播放为Run(向前跑的动画)
3.对于跳、和潜行
int r = Random.Range(0, 50);
animator.SetBool(“Jump”, r == 20);//第二项返回true或false,使参数的设置是随机的
animator.SetBool(“Dive”, r ==30);
注:几个要注意的点:
Dot(currentDir, wantedDir)//判断左右 点积大于0,目标方向在右,小于0,在左
Cross(currentDir,wantedDir).y//叉积判断前后
public class CrowdMovement : MonoBehaviour {
public float AvatarRange = 25;
private Animator animator;
private float SpeedDampTime = 0.25f;
private float DirectionDampTime = 0.25f;
private Vector3 TargetPosition = Vector3.zero;
// Use this for initialization
void Start () {
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
if (animator == null)
return;
int r = Random.Range(0, 50);
animator.SetBool("Jump", r == 20);
animator.SetBool("Dive", r ==30);
if (Vector3.Distance(TargetPosition, animator.rootPosition) >5)
{
animator.SetFloat("Speed", 1, SpeedDampTime, Time.deltaTime);//DampTime为到达该值所需要的时间
Vector3 currentDir = animator.rootRotation * Vector3.forward;//(0,0,1) //得到当前角色方向,得到当前的方向的规范向量。
Vector3 wantedDir = (TargetPosition - animator.rootPosition).normalized;
//目标所处位置的前和后,其拐弯方式不同
if (Vector3.Dot(currentDir, wantedDir) > 0)//目标方向在前方
animator.SetFloat("Direction", Vector3.Cross(currentDir, wantedDir).y, DirectionDampTime, Time.deltaTime);
else//目标在后方,则立即右转或左转
animator.SetFloat("Direction", Vector3.Cross(currentDir, wantedDir).y > 0 ? 1 : -1, DirectionDampTime, Time.deltaTime);
}
else
{
animator.SetFloat("Speed", 0, SpeedDampTime, Time.deltaTime);
if (animator.GetFloat("Speed") < 0.01)
{
TargetPosition = new Vector3(Random.Range(-AvatarRange, AvatarRange), 0, Random.Range(-AvatarRange, AvatarRange));
}
}
}
}