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

一、框架视图

VR开发实战HTC Vive项目之枪战雇佣兵_第1张图片

二、主要代码

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 () {

    }

   
    /// 
    /// 触发事件
    /// 
    /// 
    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.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;


/// 
/// 创建敌机
/// 
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;
            }


        }


    }


    /// 
    /// 生成敌机
    /// 
    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();


    }
    
    
    void Update () {

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

        }

    }


    /// 
    /// 生成怪物
    /// 
    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().targetTransform = targetPos;

    }
}

EnemyController

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

/// 
/// 敌人控制器
/// 
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.SetDestination(targetTransform.transform.position);
        //设置随机停止距离
        navMeshAgent.stoppingDistance = Random.Range(1f, 5f);
        animator = GetComponent();


        //获取声效的组件
        audioSource = GetComponent();
        //播放跑步的声音
        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);

    }

    /// 
    /// 推迟延迟设置寻路
    /// 
    /// 
    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());
            Destroy(GetComponent());
            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()
    {
        
    }

    /// 
    /// 攻击玩家
    /// 
    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().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();
    }
    
    
    void Update () {
        
    }

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

        audioSource.Play();
    }


}

GameManager_Player

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


/// 
/// 管理类
/// 
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();
    }
    
    
    void Update () {
        
    }

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

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

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

    }



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


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


    /// 
    /// 播放飞机爆炸特效
    /// 
    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();

        currentBullet = maxBullet;
        audioSource = GetComponent();

    }
    
    
    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().AddForce(goBullet.transform.forward * bullerSpeed, ForceMode.VelocityChange); //子弹向前的力
            ////goBullet.AddComponent().velocity = goBullet.transform.forward * bullerSpeed; //给向前一个恒定的速度
            //goBullet.GetComponent().collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
            //goBullet.GetComponent().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);
        }


    }

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

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




    }

    /// 
    /// 生成子弹
    /// 
    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().AddForce(goBullet.transform.forward * bullerSpeed, ForceMode.Impulse); //子弹向前的力
                                                                                                                         //goBullet.AddComponent().velocity = goBullet.transform.forward * bullerSpeed; //给向前一个恒定的速度
        goBullet.GetComponent().collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
        goBullet.GetComponent().useGravity = false;
        Destroy(goBullet, 3f);
    }


    /// 
    /// 换子弹结束
    /// 
    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().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().pitch = 3f;
        go.transform.GetComponent().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();

        //扔炸弹
       // 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();  //设置目的地
                }
            }
        }

    }

    /// 
    /// 新目的地
    /// 
    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);
        }

    }


    /// 
    /// 扔炸弹
    /// 
    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().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();
        //}

    }


    /// 
    /// 攻击玩家
    /// 
    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().AddForce( go.transform.up*10,ForceMode.Impulse);
        Destroy(go,1f);

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

三、效果图

VR开发实战HTC Vive项目之枪战雇佣兵_第2张图片
VR开发实战HTC Vive项目之枪战雇佣兵_第3张图片
VR开发实战HTC Vive项目之枪战雇佣兵_第4张图片

你可能感兴趣的:(VR开发实战HTC Vive项目之枪战雇佣兵)