Unity3D-敌人巡逻和拉脱

agent = GetComponent();//获得导航组件

一.巡逻

agent.speed = speed * 0.5f;//巡逻状态下速度为平时移动的一般

                

//判断当前巡逻距离是否超过初始巡逻范围

if(Vector3.Distance(wayPoint, transform.position) <= agent.stoppingDistance)

{

    if(remainLookAtTime > 0)//等待时间大于0后继续巡逻

    {

        remainLookAtTime -= Time.deltaTime;

    }

    else

    {

        GetNewWayPoint();

    }

}

else

{

    isWalk = true;

    agent.destination = wayPoint;

}

void GetNewWayPoint()

{

remainLookAtTime = lookAtTime;//设置停留时间

    float randomX = Random.Range(-patrolRange, patrolRange);//获得指定范围X坐标随机数

    float randomZ = Random.Range(-patrolRange, patrolRange);//获得指定范围Y坐标随机数

    Vector3 randomPoint = new Vector3(guardPos.x + randomX, transform.position.y, guardPos.z + randomZ);

    NavMeshHit hit;

    wayPoint =  NavMesh.SamplePosition(randomPoint, out hit, patrolRange, 1) ? hit.position : transform.position;//如果随机移动的坐标是可经过的则移动,否则停留到当前的坐标

}

private void OnDrawGizmosSelected()//绘制巡逻可视区域

{

    Gizmos.color = Color.blue;

    Gizmos.DrawWireSphere(transform.position, sightRadius);

}

  • 拉脱(意思是敌人追踪的目标丢失)

//当敌人丢失目标后

if(transform.position != guardPos)//判断当前不处于起始位置

{

    agent.isStopped = false;

agent.destination = guardPos;

//是否回到起始位置

    if(Vector3.SqrMagnitude(guardPos - transform.position) <= agent.stoppingDistance)

    {

        transform.rotation = Quaternion.Lerp(transform.rotation, guardRotation, 0.01f);

    }

}

你可能感兴趣的:(unity3d,c#)