unity_小功能实现(敌人巡逻功能)

 

利用NavMeshAgent控制敌人巡逻,即敌人在一组位置间循环巡逻。

 

首先我们要知道NavMeshAgent中有两个方法:1.锁定当前巡逻的某一目标位置,即navMeshAgent.destination

 

2.到达目标位置停止巡逻(休息一定时间继续巡逻),即navMeshAgent.Stop();

 

代码实现如下:

 

usingUnityEngine;

usingSystem.Collections;

using UnityEngine.AI;

 

public class EnemyMoveAI : MonoBehaviour {

 

public Transform[] directPoints; //0-3

privateint index = 0;

    public float patroTime = 3f;//到达某一点停止等待时间

    private float timer = 0;//计时器

 

privateNavMeshAgentnavMeshAgent;

 

 

void Awake()

    {

navMeshAgent = GetComponent<NavMeshAgent>();

navMeshAgent.destination = directPoints[index].position;

    }

 

void Update()

    {  

if (navMeshAgent.remainingDistance< 0.5f)

        {

timer += Time.deltaTime;

if (timer==patroTime)

            {

index++;

                index %= 4;//在4个点之间循环巡逻

timer = 0;

navMeshAgent.destination = directPoints[index].position;

            }

        }

    }

 

}

 

注意:

 

1.为了保证敌人能在该组点内循环巡逻(而不是只巡逻一圈),采用取余的方式获得点数组的下标。

 

2.没有使用navMeshAgent.Stop();原因是,如果使用了则到达一个巡逻点后敌人将不会再向新的目标点移动。

转载于:https://www.cnblogs.com/shirln/p/9105556.html

  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现敌人的自动巡逻攻击,您需要按照以下步骤进行: 1. 创建一个敌人角色和一个玩家角色。您可以使用Unity中的基本形状或导入自己的3D模型。 2. 在敌人角色上添加一个脚本,以便它可以寻找并攻击玩家。在脚本中,您需要定义敌人的移动方式和攻击方式。 3. 在脚本中添加一个检测玩家的函数。您可以使用Unity提供的Collider或Raycast来检测玩家是否在敌人的视野范围内。 4. 如果敌人检测到玩家,它应该开始朝玩家移动并攻击。您可以使用Unity的导航系统来实现敌人的移动,使用动画来实现攻击。 5. 您还可以添加一些额外的功能,例如敌人的血量和死亡动画。 下面是一个简单的示例代码: ``` public class EnemyController : MonoBehaviour { public float speed = 5f; public float attackDistance = 2f; public float attackCooldown = 2f; public float health = 100f; private Transform player; private NavMeshAgent navMeshAgent; private Animator animator; private bool attacking = false; void Start () { player = GameObject.FindGameObjectWithTag("Player").transform; navMeshAgent = GetComponent<NavMeshAgent>(); animator = GetComponent<Animator>(); } void Update () { if (health <= 0) { Die(); return; } if (Vector3.Distance(transform.position, player.position) < attackDistance) { if (!attacking) { StartCoroutine(Attack()); } } else { navMeshAgent.SetDestination(player.position); animator.SetBool("Walking", true); } } IEnumerator Attack() { attacking = true; animator.SetBool("Walking", false); animator.SetBool("Attacking", true); yield return new WaitForSeconds(attackCooldown); animator.SetBool("Attacking", false); attacking = false; } public void TakeDamage(float damage) { health -= damage; } void Die() { animator.SetBool("Dead", true); navMeshAgent.enabled = false; Destroy(gameObject, 2f); } } ``` 在这个示例代码中,敌人会在玩家进入攻击范围时启动攻击动画。当敌人的血量降至0时,它会播放死亡动画并在2秒后销毁。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值