VR开发实战HTC Vive项目之枪战雇佣兵

一、框架视图

二、主要代码

BulletVR

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class BulletVR : MonoBehaviour {

    //飞机碎片
    public GameObject AirPieces;

    //火花特效
    public GameObject spark;

    void Start () {
        
    }
    
    
    void Update () {

    }

   
    /// <summary>
    /// 触发事件
    /// </summary>
    /// <param name="coll"></param>
    void OnTriggerEnter(Collider coll)
    {
        if (coll.transform.tag == "Enemy")
        {
          GameObject go=  GameObject.Instantiate(AirPieces, coll.transform);
            go.transform.SetParent(null);

            GameManager_Player.Instance.PlayAirExplosion(); //播放飞机爆炸的音效
            Destroy(coll.transform.gameObject);

            //Debug.Log("打中了···");
            //敌机的分数加一
            GameManager_Player.Instance.cutrrent_Air += 1;
            GameManager_Player.Instance.textMesh_Air.text = "摧毁敌机:"+GameManager_Player.Instance.cutrrent_Air+"架";
        }
        else if (coll.transform.tag== "Soldier")
        {
            EnemyController _enemyController = coll.transform.gameObject.GetComponent<EnemyController>();
            _enemyController.UnderAttack(); //敌人被玩家击中时调用的函数
            GameObject _Spark = GameObject.Instantiate(spark,coll.transform); //播放火花击中特效
            _Spark.transform.position = coll.transform.position;
            Destroy(_Spark,3);
        }
        else if (coll.transform.tag=="RePlay")
        {
            GameManager_Player.Instance.RestartGame(); //重新加载游戏
        }
        else if (coll.transform.name== "ReLoad")
        {
            SceneManager.LoadScene("SpaceShooter");
        }
        
    }


}

CreatAirPlane


using System.Collections;
using System.Collections.Generic;
using UnityEngine;


/// <summary>
/// 创建敌机
/// </summary>
public class CreatAirPlane : MonoBehaviour {

    //产生敌机的预制体
    public GameObject[] planePrefabs;

    //最长刷机时长
    private   float maxCloudDownTime = 4f;

    //最短刷机时长
    private   float minCloudDownTime = 1f;

    //当前时长
    private float currentClodTime;

    void Start () {

        //初次刷机时长
        // currentClodTime = minCloudDownTime;
        currentClodTime = Random.Range(5,minCloudDownTime);
    }
    
    void Update () {

        currentClodTime -= Time.deltaTime;
        //当冷却时间完成后创建敌机并减少刷机的冷却时间
        if (currentClodTime<=0)
        {
            IntantiateAirPlane();
            currentClodTime = maxCloudDownTime;
            if (maxCloudDownTime>minCloudDownTime)
            {
                maxCloudDownTime -= 0.5f;
            }


        }


    }


    /// <summary>
    /// 生成敌机
    /// </summary>
    private void IntantiateAirPlane()
    {
        //创建敌机
        GameObject _airPlane = Instantiate(planePrefabs[Random.Range(0,planePrefabs.Length)]);
        //吧创建的飞机放在自己的下面 方便管理
        _airPlane.transform.parent = this.transform;

    }

   

}

CreateSoilder_Spawn


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//创建敌人
public class CreateSoilder_Spawn : MonoBehaviour {


    //产生士兵的预制体
    public GameObject[] monsterPrefabs;

    //目标位置
    public Transform targetPos;

    public Transform[] enemyPos;


    //创建时播放的声音文件
    //public AudioClip clip;
    //AudioSource audioSource;

    //最长刷怪时长
    private float maxClodDownTime=10;
    //最短刷怪时长
    private float minClodDownTime = 2;
    //当前时长
    private float currentClodDownTime;

    void Start () {

        //初始化下次刷怪
        currentClodDownTime = Random.Range(1,minClodDownTime)*0.5f;
        //获取声效的组件
       // audioSource = GetComponent<AudioSource>();


    }
    
    
    void Update () {

        //获取每一帧的执行时间
        currentClodDownTime -= Time.deltaTime*1f;
        //当冷却时间完成后创建怪物并减少刷怪的冷却时间
        if (currentClodDownTime<=0)
        {
            InstantiateMoster();
            currentClodDownTime = maxClodDownTime;
            if (maxClodDownTime>minClodDownTime)
            {
                maxClodDownTime -= 0.5f;
            }

        }

    }


    /// <summary>
    /// 生成怪物
    /// </summary>
    private void InstantiateMoster()
    {
        //播放怪物的声音
        // audioSource.PlayOneShot(clip);
        //创建怪物   
         GameObject _Monster = Instantiate(monsterPrefabs[Random.Range(0,monsterPrefabs.Length)]);
        //GameObject _Monster = Instantiate(monsterPrefabs[Random.Range(0, monsterPrefabs.Length)], enemyPos[Random.Range(0, enemyPos.Length)].position,Quaternion.identity);
        //把创建的怪物放到自己下面 方便管理
        // _Monster.transform.parent = this.transform;
        Transform _transform= enemyPos[Random.Range(0, enemyPos.Length)];
        _Monster.transform.parent = _transform;
        //通过随机放置怪物在传送门的位置
        _Monster.transform.position = _transform.position + new Vector3(UnityEngine.Random.Range(-5,5),1.5f,UnityEngine.Random.Range(-2.5f,2.5f));

       // Debug.Log("敌人位置" + _Monster.transform.position);
        _Monster.GetComponent<EnemyController>().targetTransform = targetPos;

    }
}

EnemyController

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

/// <summary>
/// 敌人控制器
/// </summary>
public class EnemyController : MonoBehaviour
{

    //目标位置
    [HideInInspector]
    public Transform targetTransform;

    //敌人总血量
    int HP = 2;
    //寻路组件
    NavMeshAgent navMeshAgent;
    //动画
    Animator animator;
    //AnimatorStateInfo stateInfo;
    AnimatorClipInfo[] stateInfo;

    //子弹预制体
    public GameObject Bullet_S;

    //枪口的位置
    public GameObject GunPoint;

    //动画信息
    AnimatorStateInfo animatorInfo;

    AudioSource audioSource;
    //播放士兵跑步的声音
    public AudioClip runClip;

    //播放士兵受伤的声音
    public AudioClip hitClip;
    //播放士兵跑步的声音
    public AudioClip deathClip;

    //随机攻击的距离
    public float remainingDis;
    //随机停止的距离
    public float stopDis;

    void Start()
    {
        //初始化
        //获取寻路组件
        navMeshAgent = GetComponent<NavMeshAgent>();
        //设置目的地
        navMeshAgent.SetDestination(targetTransform.transform.position);
        //设置随机停止距离
        navMeshAgent.stoppingDistance = Random.Range(1f, 5f);
        animator = GetComponent<Animator>();


        //获取声效的组件
        audioSource = GetComponent<AudioSource>();
        //播放跑步的声音
        audioSource.loop = true;
         audioSource.PlayOneShot(runClip);

        remainingDis = Random.Range(6,20);

        

    }


    void Update()
    {
   
        //死亡直接返回
        if (HP <= 0)
        {
            return;
        }
        ////获取当前动画信息
        //AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(0);

        ////判断当前的动画状态是什么,并进行对应的处理
        //if (stateInfo.fullPathHash == Animator.StringToHash("Base Layer.Run_Rifle_2N") && !animator.IsInTransition(0))
        //{
        //    animator.SetBool("Run", false);
        //    //玩家有移动重新检测,目前不会移动
        //    if (Vector3.Distance(targetTransform.transform.position, navMeshAgent.destination) > 1)
        //    {
        //        navMeshAgent.SetDestination(targetTransform.transform.position);
        //    }
        //    //进入攻击距离跳转到攻击动画,否则继续跑动
        //    if (navMeshAgent.remainingDistance < 10)
        //    {
        //        animator.SetBool("Attack", true);
        //        navMeshAgent.isStopped = true;
        //    }
        //    else
        //    {
        //        animator.SetBool("Run", true);
        //        navMeshAgent.isStopped = false;
        //    }
        //}

        //if (stateInfo.fullPathHash == Animator.StringToHash("Base Layer.Idle_Shoot") && !animator.IsInTransition(0))
        //{
        //    animator.SetBool("Attack", false);
        //    //玩家有移动重新检测,目前不会移动
        //    if (Vector3.Distance(targetTransform.transform.position, navMeshAgent.destination) > 1)
        //    {
        //        navMeshAgent.SetDestination(targetTransform.transform.position);
        //    }
        //    //进入攻击距离跳转到攻击动画,否则继续跑动
        //    //if (navMeshAgent.remainingDistance < 10)
        //    //{
        //    //    animator.SetBool("Attack", true);
        //    //   // navMeshAgent.Stop();
        //    //    navMeshAgent.isStopped = true;
        //    //}
        //    //else
        //    //{
        //    //    animator.SetBool("Run", true);
        //    //    navMeshAgent.isStopped = false;
        //    //}


        //}

        //if (stateInfo.fullPathHash == Animator.StringToHash("Base Layer.Hit_Left") && !animator.IsInTransition(0))
        //{
        //    animator.SetBool("Attack", false);
        //    animator.SetBool("Run", false);
        //    //玩家有移动重新检测,目前不会移动
        //    if (Vector3.Distance(targetTransform.transform.position, navMeshAgent.destination) > 1)
        //    {
        //        navMeshAgent.SetDestination(targetTransform.transform.position);
        //    }
        //    //进入攻击距离跳转到攻击动画,否则继续跑动
        //    if (navMeshAgent.remainingDistance < 10)
        //    {
        //        animator.SetBool("Attack", true);
        //        // navMeshAgent.Stop();
        //        navMeshAgent.isStopped = true;
        //    }
        //    else
        //    {
        //        animator.SetBool("Run", true);
        //    }
        //}

        //玩家有移动 重新检测
        if (Vector3.Distance(targetTransform.transform.position, navMeshAgent.destination) > 10)
        {
            navMeshAgent.SetDestination(targetTransform.transform.position);
            animator.SetBool("Run", true);
        }
        //进入攻击距离跳转到攻击动画,否则继续跑动
        if (navMeshAgent.remainingDistance < remainingDis)
        {
            animator.SetBool("Attack", true);
            animator.SetBool("Run", false);
            navMeshAgent.isStopped = true;
        }
        else
        {
            animator.SetBool("Run", true);
            navMeshAgent.isStopped = false;
        }
        //朝向目标
        transform.LookAt(targetTransform);

    }

    /// <summary>
    /// 推迟延迟设置寻路
    /// </summary>
    /// <returns></returns>
    IEnumerator DelaySetBool() {
      //  Debug.Log("延迟了几秒::"+animatorInfo.normalizedTime);
        yield return new WaitForSeconds(animatorInfo.normalizedTime);
        if (navMeshAgent != null)
        {
            navMeshAgent.isStopped = false; //寻路停止
            
        }

    }




    //敌人当被枪击中时
    public void UnderAttack()
    {
        //扣血并且判断是否挂掉  如果死亡 直接跳转死亡动画  否则跳转受伤动画
        HP--;
        if (HP <= 0)
        {
            animator.Play("Death");
            audioSource.loop = false;
            audioSource.PlayOneShot(deathClip);
            Destroy(GetComponent<Collider>());
            Destroy(GetComponent<NavMeshAgent>());
            Destroy(gameObject,3);

            //把分数传送回去
            GameManager_Player.Instance.current_Enemy += 1;
            GameManager_Player.Instance.textMesh_Enemy.text = "消灭敌人:"+GameManager_Player.Instance.current_Enemy+"个";

        }
        else
        {
            animator.Play("Hit_Left");  //播放敌人受伤动画
            audioSource.loop = false;
            audioSource.PlayOneShot(hitClip);
            // animator.SetBool("Hit", true);
            navMeshAgent.isStopped = true; //寻路停止
            animatorInfo = animator.GetCurrentAnimatorStateInfo(0);
            StartCoroutine(DelaySetBool());
        }

    }


    //怪物攻击  动画事件中去调用
    public void Attack()
    {
        
    }

    /// <summary>
    /// 攻击玩家
    /// </summary>
    public void AttackPlayer()
    {

        GameObject go = Instantiate(Bullet_S, Vector3.zero, Quaternion.identity);//实例化子弹
        go.transform.SetParent(GunPoint.transform);
        go.transform.localPosition = Vector3.zero;
        go.transform.localEulerAngles = Vector3.zero;
        go.GetComponent<Rigidbody>().AddForce(go.transform.forward * 10, ForceMode.Impulse); //设置设计速度
        Destroy(go, 1f);

        // Debug.Log("是否执行了实例化子弹");

        //减少玩家的血量
        GameManager_Player.Instance.UnderAttack(); //单例调用的方法

    }


}


GameManager_Gun

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//单例模式  
public class GameManager_Gun : MonoBehaviour {

    public static GameManager_Gun Instance;

    private AudioSource audioSource;

    public GameObject audioManager;

    void Awake() {
        Instance = this;
    }

    void Start () {

        audioSource = audioManager.GetComponent<AudioSource>();
    }
    
    
    void Update () {
        
    }

    /// <summary>
    /// 播放飞机爆炸特效
    /// </summary>
    public void PlayAirExplosion() {

        audioSource.Play();
    }


}

GameManager_Player

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;


/// <summary>
/// 管理类
/// </summary>
public class GameManager_Player : MonoBehaviour {

    //单例模式
    public static GameManager_Player Instance;

    //当前玩家血量
    public int CurrentHP = 1000;
    //显示玩家生命值
    public TextMesh textMesh_Hp;

    //当前敌机的数量
    public int cutrrent_Air = 0;
    //销毁敌机的数量
    public TextMesh textMesh_Air;

    //当前销货敌人的数量
    public int current_Enemy=0;
    //销毁敌人的数量
    public TextMesh textMesh_Enemy;

    //怪物传送门
    public GameObject SpawnEnemy;

    //敌机传送门
    public GameObject SpawmAirPlane;

    //重新开始
    public GameObject rePlay;

    //声音管理
    private AudioSource audioSource;
    //获取声音对象
    public GameObject audioManager;

    void Awake() {
        Instance = this;
    }


    void Start () {
        audioSource = audioManager.GetComponent<AudioSource>();
    }
    
    
    void Update () {
        
    }

    /// <summary>
    /// 受到怪物攻击时
    /// </summary>
    public void UnderAttack() {

        CurrentHP--;
        textMesh_Hp.text ="生命值:"+ CurrentHP+"//1000";

       // Debug.Log("玩家血量::"+CurrentHP);
        //如果血量小于0 GameOver
        if (CurrentHP<=0)
        {
            GameOver();
        }

    }



    /// <summary>
    /// y游戏结束
    /// </summary>
    private void GameOver()
    {
        Destroy(SpawnEnemy); //销毁敌人传送点
        Destroy(SpawmAirPlane);  //销毁敌机传送点
        rePlay.SetActive(true);
    }


    /// <summary>
    /// 重现加载本场景
    /// </summary>
    public void RestartGame() {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }


    /// <summary>
    /// 播放飞机爆炸特效
    /// </summary>
    public void PlayAirExplosion()
    {

        audioSource.Play();
    }
}

GunManager

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GunManager : MonoBehaviour {

    //定义枪的起始位置 为了获取枪口的位置
    public Transform gunPoint;

    //枪的特效
    private  LineRenderer  lineRenderer;  //先渲染器组件

    //瞄准点
    public GameObject rayPoint;

    //射击音效
   // public AudioSource audioSource;

    //射线
    Ray ray;
    RaycastHit hit;

    public GameObject ctrlPlane;

    //子弹预制体
    public GameObject bulletPrefab;
    //用来贮存生成的子弹
    private GameObject goBullet;
    //子弹生成的位置
    private Vector3 bulletPos;
    private Vector3 bulletRote;
    //子弹速度
    public float bullerSpeed=10;

    //狙击镜的缩放
    public const float minFov=10f;
    public const float maxFov = 90f;
    //狙击镜
    public Camera cameraScope;

    public float fov; //获取数值
    public float _fov;//变化数值
    public bool isFov;

    public bool isForward; //向前推
    public bool isBack;//向后推


   

    //显示子弹数量
    public TextMesh textMesh_Bullet;



    //开火的声效
    public AudioClip fire;

    //换弹声效
    public AudioClip reLoad;


    private AudioSource audioSource;

    //是否在换弹中
    private bool isReloading=false;

    //最大子弹数与当前子弹数
    int maxBullet = 1000;
    int currentBullet;


    void Start () {

        lineRenderer = GameObject.Find("GunPoint").transform.GetComponent<LineRenderer>();

        currentBullet = maxBullet;
        audioSource = GetComponent<AudioSource>();

    }
    
    
    void Update () {

        //ray = new Ray(gunPoint.position, gunPoint.forward); //反射位置 发射方向

        //lineRenderer.SetPosition(0, gunPoint.position);
        ////line.SetPosition(1, ray.direction * 100);

        //if (Physics.Raycast(ray, out hit, 100))
        //{
        //    //把瞄准点显示出来
        //    rayPoint.SetActive(true);
        //    //瞄准点的位置就是碰撞到的位置
        //    rayPoint.transform.position = hit.point;
        //    //特效线的末尾位置 就是碰撞点的位置
        //    lineRenderer.SetPosition(1, hit.point);
           


        //    if (hit.transform.tag == "CtrlPlane")
        //    {
        //        if (Input.GetMouseButtonDown(0))
        //        {
        //            ctrlPlane.SetActive(false);
        //        }

        //    }

        //}
        //else
        //{
        //    //没有碰到碰撞点隐藏
        //    rayPoint.SetActive(false);
        //    //如果没碰到就发射到 一条线即可
        //    lineRenderer.SetPosition(1, ray.direction * 100);
        //}


       // Debug.DrawRay(gunPoint.position, gunPoint.forward * 10, Color.blue);

        //发射子弹
        if (Input.GetMouseButtonDown(0))        
        {
            //bulletPos = GameObject.Find("GunPoint").transform.position; //注意生成的位置
            //bulletRote = GameObject.Find("GunPoint").transform.eulerAngles;//注意生成的角度

            //goBullet = GameObject.Instantiate(bulletPrefab,bulletPos,Quaternion.identity); 
            //goBullet.transform.eulerAngles = bulletRote;
            //goBullet.AddComponent<Rigidbody>().AddForce(goBullet.transform.forward * bullerSpeed, ForceMode.VelocityChange); //子弹向前的力
            ////goBullet.AddComponent<Rigidbody>().velocity = goBullet.transform.forward * bullerSpeed; //给向前一个恒定的速度
            //goBullet.GetComponent<Rigidbody>().collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
            //goBullet.GetComponent<Rigidbody>().useGravity = false;
            //Destroy(goBullet,3f);
            GunFire();

        }

        //控制狙击镜缩放---按键控制

        if (Input.GetKeyDown(KeyCode.W))
        {
            isForward = true;
            isFov = true;
        }
        else if (Input.GetKeyUp(KeyCode.W))
        {
            fov = 0;
            isForward = false;
            isFov = false;
        }
        else if (Input.GetKeyDown(KeyCode.S))
        {
            isBack = true;
            isFov = true;
        }
        else if (Input.GetKeyUp(KeyCode.S))
        {
            fov = 0;
            isBack = false;
            isFov = false;
        }


        if (isFov)
        {
           
            if (isBack)
            {
                fov += Time.deltaTime * 50;
                fov = 0 - fov;
            }
            if (isForward)
            {
                fov += Time.deltaTime * 0.5f;
            }
            
            _fov = cameraScope.fieldOfView - fov;
            if (_fov <= minFov)
            {
                cameraScope.fieldOfView = minFov;
            }
            else if (_fov >= maxFov)
            {
                cameraScope.fieldOfView = maxFov;
            }
            else
            {
                cameraScope.fieldOfView = _fov;
            }
            //_fov = Mathf.Clamp(fov,minFov,maxFov);
            //cameraScope.fieldOfView = _fov;

        }
        //狙击镜缩放-------完毕

        //按下 向上的键 换枪
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            //如果在换弹中 直接返回
            if (isReloading)
            {
                return;
            }

            isReloading = true;

            Invoke("ReloadFinished",2);

            audioSource.PlayOneShot(reLoad);
        }


    }

    /// <summary>
    /// 控制开枪的逻辑
    /// </summary>
    public void GunFire() {

        //如果在换弹中 直接返回
        if (isReloading)
        {
            return;
        }
        //如果当前子弹大于0 子弹减少并且显示在3D Text上
        if (currentBullet>0)
        {
            currentBullet--;
            textMesh_Bullet.text = currentBullet.ToString();
            InstantiateBullet();//实力子弹
           // audioSource.PlayOneShot(fire); //播放声效也以及动画
        }
        else
        {
            //如果没有子弹也直接返回
            return;
        }




    }

    /// <summary>
    /// 生成子弹
    /// </summary>
    public void InstantiateBullet() {
        bulletPos = GameObject.Find("GunPoint").transform.position; //注意生成的位置
        bulletRote = GameObject.Find("GunPoint").transform.eulerAngles;//注意生成的角度

        goBullet = GameObject.Instantiate(bulletPrefab, bulletPos, Quaternion.identity);
        goBullet.transform.eulerAngles = bulletRote;
        goBullet.AddComponent<Rigidbody>().AddForce(goBullet.transform.forward * bullerSpeed, ForceMode.Impulse); //子弹向前的力
                                                                                                                         //goBullet.AddComponent<Rigidbody>().velocity = goBullet.transform.forward * bullerSpeed; //给向前一个恒定的速度
        goBullet.GetComponent<Rigidbody>().collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
        goBullet.GetComponent<Rigidbody>().useGravity = false;
        Destroy(goBullet, 3f);
    }


    /// <summary>
    /// 换子弹结束
    /// </summary>
    private void ReloadFinished() {

        isReloading = false;
        currentBullet = maxBullet;
        textMesh_Bullet.text = currentBullet.ToString();
    }

}

MissileCtrl

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MissileCtrl : MonoBehaviour {


    public GameObject explosionPrefab;

    GameObject go;

    void Start () {

        Invoke("DestroyGo", 20f);
    }
    
    
    void Update () {
        
    }

    //碰撞发生时候执行一次
    void OnCollisionEnter(Collision coll)
    {

       
        if (coll.gameObject.tag=="Floor")
        {
            //Debug.Log("Enter" + coll.gameObject.name);
            go = Instantiate(explosionPrefab, this.transform);
            go.transform.SetParent(null);
            go.SetActive(false);
            this.transform.GetComponent<Rigidbody>().AddForceAtPosition(Vector3.right*Random.Range(0.5f,5f),coll.transform.position,ForceMode.Force);
            StartCoroutine(StartExplosion());
        }
        else
        {
            Destroy(gameObject);
        }

    }


    IEnumerator StartExplosion() {

        yield return new WaitForSeconds(1.5f);
        //调用受攻击的函数
        GameManager_Player.Instance.UnderAttack();
        go.SetActive(true);
        //go.transform.GetComponent<AudioSource>().pitch = 3f;
        go.transform.GetComponent<AudioSource>().Play();
        Destroy(go,4f);
        gameObject.SetActive(false);
        Destroy(gameObject,10f);
    }


    public void DestroyGo() {

        if (gameObject!=null)
        {
            
            Destroy(gameObject);
        }
    }



}

RandomAgent

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;


//飞机随机寻路点
[RequireComponent(typeof(NavMeshAgent))]
public class RandomAgent : MonoBehaviour {

    //设置飞机寻路点
    private NavMeshAgent agent;


    //导弹预制体
    public GameObject missilePrefab;

    //导弹的数量
    public int missileCount=6;





    void Start() {

        agent = GetComponent<NavMeshAgent>();

        //扔炸弹
       // InvokeRepeating("ThrowBomb", 1, 2);
    }

    // Update is called once per frame
    void Update() {

        if (!agent.pathPending)
        {
            if (agent.remainingDistance <= agent.stoppingDistance)
            {
                if (!agent.hasPath || agent.velocity.sqrMagnitude == 0f)
                {
                    NewDestination();  //设置目的地
                }
            }
        }

    }

    /// <summary>
    /// 新目的地
    /// </summary>
    private void NewDestination() {
        Vector3 newDest = Random.insideUnitSphere * 500f + new Vector3(139f, 86f, -172f);
        NavMeshHit hit;
        bool hasDestination = NavMesh.SamplePosition(newDest, out hit, 100f, 1);
        if (hasDestination)
        {
            agent.SetDestination(hit.position);
        }

    }


    /// <summary>
    /// 扔炸弹
    /// </summary>
    public void ThrowBomb() {

        for (int i = 0; i < missileCount; i++)
        {
            GameObject go = Instantiate(missilePrefab, new Vector3(transform.position.x + i * 2, transform.position.y + i * 2, transform.position.z), Quaternion.identity);

            go.transform.localEulerAngles = new Vector3(0, 45, 0);
        }
    }


    //进入触发器范围内执行一次
    void OnTriggerEnter(Collider coll)
    {

      //  Debug.Log("Cube Enter" + coll.gameObject.name);
        if (coll.gameObject.name== "BombRange")
        {
            //扔炸弹
             InvokeRepeating("ThrowBomb", 2, 4);
        }

    }

    //离开触发器范围后执行一次
    void OnTriggerExit(Collider coll)
    {

       // Debug.Log("Cube Exit" + coll.gameObject.name);
        if (coll.gameObject.name == "BombRange")
        {
            CancelInvoke("ThrowBomb");

            Destroy(gameObject,6.5f);
        }
    }


}

Sniper

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Sniper : MonoBehaviour {

    public GameObject bulletPrefab;

    public Transform bulletSpwanPoint;

    void Start () {
    
        
    }
    
    
    void Update () {

        if (Input.GetMouseButtonDown(0))
        {
            GameObject go = Instantiate(bulletPrefab,bulletSpwanPoint.position,bulletSpwanPoint.rotation) as GameObject;
            go.transform.Rotate(90f,0f,0f);
            go.transform.GetComponent<Rigidbody>().velocity = 1000 * bulletSpwanPoint.transform.forward;

        }

    }
}

Soilder

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Soilder : MonoBehaviour {

    //子弹预制体
    public GameObject Bullet_S;
    //枪口位置
    public GameObject GunPoint; 

    void Start () {
        
    }
    
    
    void Update () {

        //if (Input.GetMouseButtonDown(0))
        //{
        //    ShootPlayer();
        //}

    }


    /// <summary>
    /// 攻击玩家
    /// </summary>
    public void ShootPlayer() {

        GameObject go = Instantiate(Bullet_S,Vector3.zero,Quaternion.identity);
        go.transform.SetParent(GunPoint.transform);
        go.transform.localPosition = Vector3.zero;
        go.transform.localEulerAngles = Vector3.zero;
        go.GetComponent<Rigidbody>().AddForce( go.transform.up*10,ForceMode.Impulse);
        Destroy(go,1f);

       // Debug.Log("执行了吗,啊?");
    }
}

三、效果图

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容