博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Survival Shooter 学习
阅读量:6705 次
发布时间:2019-06-25

本文共 21853 字,大约阅读时间需要 72 分钟。

 

using UnityEngine;using System.Collections;namespace CompleteProject{    ///     /// 摄像机跟随    ///     public class CameraFollow : MonoBehaviour    {        ///         /// 摄像机跟随的目标        ///         public Transform target;                    ///         /// 相机的移动速度        ///         public float smoothing = 5f;                ///         /// 摄像机相对于目标的偏移        ///         Vector3 offset;                             void Start ()        {            //计算偏移            offset = transform.position - target.position;        }        void FixedUpdate ()        {            //计算相机要移动到的位置            Vector3 targetCamPos = target.position + offset;            //移动相机            transform.position = Vector3.Lerp (transform.position, targetCamPos, smoothing * Time.deltaTime);        }    }}
CameraFollow

 

using UnityEngine;namespace CompleteProject{    ///     /// 敌人管理    ///     public class EnemyManager : MonoBehaviour    {        ///         /// 玩家生命        ///         public PlayerHealth playerHealth;               ///         /// 敌人预设        ///         public GameObject enemy;                        ///         /// 每次孵化敌人的间隔        ///         public float spawnTime = 3f;                    ///         /// 孵化敌人的位置        ///         public Transform[] spawnPoints;                  void Start ()        {            InvokeRepeating ("Spawn", spawnTime, spawnTime);        }        ///         /// 孵化敌人        ///         void Spawn ()        {            //如果玩家当前生命<=0,不处理            if(playerHealth.currentHealth <= 0f)            {                return;            }            //随机找一个孵化点            int spawnPointIndex = Random.Range (0, spawnPoints.Length);            //在这个孵化点孵化敌人            Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);        }    }}
EnemyManager
using UnityEngine;using System.Collections;namespace CompleteProject{    ///     /// 玩家攻击    ///     public class EnemyAttack : MonoBehaviour    {        ///         /// 每次攻击的时间间隔        ///         public float timeBetweenAttacks = 0.5f;             ///         /// 每次攻击照成的伤害        ///         public int attackDamage = 10;                       ///         /// 敌人Animator        ///         Animator anim;                                      ///         /// 玩家        ///         GameObject player;                                  ///         /// 玩家生命        ///         PlayerHealth playerHealth;                          ///         /// 敌人生命        ///         EnemyHealth enemyHealth;                            ///         /// 玩家是否在攻击范围内        ///         bool playerInRange;                                 ///         /// 下次攻击的计时器        ///         float timer;                                                                    void Awake ()        {            player = GameObject.FindGameObjectWithTag ("Player");            playerHealth = player.GetComponent 
(); enemyHealth = GetComponent
(); anim = GetComponent
(); } void OnTriggerEnter (Collider other) { //如果碰到玩家 if(other.gameObject == player) { //设置标志位为true playerInRange = true; } } void OnTriggerExit (Collider other) { //如果玩家离开 if(other.gameObject == player) { //设置标志位为false playerInRange = false; } } void Update () { //每帧增加计时器的时间 timer += Time.deltaTime; //当计时器的时间大于等于每次攻击的时间间隔 //玩家在攻击范围内 //敌人的当前血量大于0 if(timer >= timeBetweenAttacks && playerInRange && enemyHealth.currentHealth > 0) { //攻击 Attack (); } //如果玩家的生命值小于等于0 if(playerHealth.currentHealth <= 0) { //animator触发PlayerDead动画 anim.SetTrigger ("PlayerDead"); } } ///
/// 攻击 /// void Attack () { //重置攻击计时器 timer = 0f; //如果玩家当前生命大于0 if(playerHealth.currentHealth > 0) { //伤害玩家 playerHealth.TakeDamage (attackDamage); } } }}
EnemyAttack
using UnityEngine;namespace CompleteProject{    public class EnemyHealth : MonoBehaviour    {        ///         /// 敌人初始生命        ///         public int startingHealth = 100;                    ///         /// 敌人当前生命        ///         public int currentHealth;                           ///         /// 敌人死亡后下沉的速度        ///         public float sinkSpeed = 2.5f;                      ///         /// 被玩家击杀时,玩家获得的得分        ///         public int scoreValue = 10;                         ///         /// 死亡声音        ///         public AudioClip deathClip;                         Animator anim;                                      AudioSource enemyAudio;                             ///         /// 敌人受到伤害时的粒子系统        ///         ParticleSystem hitParticles;                        CapsuleCollider capsuleCollider;                    ///         /// 敌人是否死亡        ///         bool isDead;                                        ///         /// 敌人是否下沉        ///         bool isSinking;                                                    void Awake ()        {            anim = GetComponent 
(); enemyAudio = GetComponent
(); hitParticles = GetComponentInChildren
(); capsuleCollider = GetComponent
(); //设置当前生命为初始生命 currentHealth = startingHealth; } void Update () { //如果敌人在下沉 if(isSinking) { //移动敌人在y轴的位置 transform.Translate (-Vector3.up * sinkSpeed * Time.deltaTime); } } ///
/// 受到伤害 /// ///
伤害数值 ///
受到伤害的位置 public void TakeDamage (int amount, Vector3 hitPoint) { //如果敌人死亡,不处理 if(isDead) return; //播放受伤声音 enemyAudio.Play (); //减少当前血量 currentHealth -= amount; //将受伤的粒子系统的位置设置为受到伤害的位置 hitParticles.transform.position = hitPoint; //播放粒子系统 hitParticles.Play(); //如果当前血量<=0 if(currentHealth <= 0) { //调用死亡函数 Death (); } } ///
/// 死亡 /// void Death () { //修改死亡标志位 isDead = true; //将碰撞器改为触发器 capsuleCollider.isTrigger = true; //触发animator的dead动画 anim.SetTrigger ("Dead"); //播放敌人死亡声音 enemyAudio.clip = deathClip; enemyAudio.Play (); } ///
/// 敌人开始下沉 /// public void StartSinking () { //关闭NavMeshAgent GetComponent
().enabled = false; //将Rigidbody设置为kinematic GetComponent
().isKinematic = true; //将下沉标志位设置为true isSinking = true; //添加玩家的得分 ScoreManager.score += scoreValue; //销毁敌人 Destroy (gameObject, 2f); } }}
EnemyHealth
using UnityEngine;using System.Collections;namespace CompleteProject{    ///     /// 敌人移动    ///     public class EnemyMovement : MonoBehaviour    {        ///         /// 玩家的位置        ///         Transform player;                       ///         /// 玩家的生命        ///         PlayerHealth playerHealth;              ///         /// 敌人生命        ///         EnemyHealth enemyHealth;                ///         /// NavMeshAgent        ///         NavMeshAgent nav;                           void Awake ()        {            player = GameObject.FindGameObjectWithTag ("Player").transform;            playerHealth = player.GetComponent 
(); enemyHealth = GetComponent
(); nav = GetComponent
(); } void Update () { //如果敌人生命和玩家生命都大于0 if(enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0) { //敌人移动到玩家位置 nav.SetDestination (player.position); } //否则关闭NavMeshAgent else { nav.enabled = false; } } }}
EnemyMovement

 

using UnityEngine;using UnityEngine.UI;using System.Collections;using UnityEngine.SceneManagement;namespace CompleteProject{    ///     /// 玩家生命    ///     public class PlayerHealth : MonoBehaviour    {        ///         /// 游戏开始时玩家的生命        ///         public int startingHealth = 100;                                  ///         /// 玩家的当前生命        ///         public int currentHealth;                                          ///         /// 生命滑动条        ///         public Slider healthSlider;                                        ///         /// 玩家受到伤害时的图片        ///         public Image damageImage;                                          ///         /// 玩家死亡的声音剪辑        ///         public AudioClip deathClip;                                        ///         /// 伤害图片变透明的速度        ///         public float flashSpeed = 5f;                                      ///         /// 伤害图片的颜色        ///         public Color flashColour = new Color(1f, 0f, 0f, 0.1f);                Animator anim;                                  AudioSource playerAudio;                                          PlayerMovement playerMovement;                                    PlayerShooting playerShooting;        ///         /// 玩家是否死亡        ///                                        bool isDead;        ///         /// 玩家是否受到伤害        ///                                                         bool damaged;                                                            void Awake ()        {            anim = GetComponent 
(); playerAudio = GetComponent
(); playerMovement = GetComponent
(); playerShooting = GetComponentInChildren
(); //设置当前血量为起始血量 currentHealth = startingHealth; } void Update () { //如果玩家受到伤害,修改伤害图片的颜色 if(damaged) { damageImage.color = flashColour; } //没有受到伤害,伤害图片渐隐 else { damageImage.color = Color.Lerp (damageImage.color, Color.clear, flashSpeed * Time.deltaTime); } //设置伤害标志位false damaged = false; } ///
/// 玩家受到伤害 /// ///
受到伤害的数值 public void TakeDamage (int amount) { //设置伤害标志位true damaged = true; //减少当前血量 currentHealth -= amount; //将当前血量应用到血量滑动条上 healthSlider.value = currentHealth; //播放受伤的声音 playerAudio.Play (); //如果当前血量<=0并且玩家死亡的标志位位true. if(currentHealth <= 0 && !isDead) { Death (); } } ///
/// 玩家死亡 /// void Death () { //修改死亡标志位 isDead = true; //关闭射击特效 playerShooting.DisableEffects (); //触发死亡动画 anim.SetTrigger ("Die"); //播放死亡声音 playerAudio.clip = deathClip; playerAudio.Play (); //关闭移动和射击脚本 playerMovement.enabled = false; playerShooting.enabled = false; } ///
/// 重新开始 /// public void RestartLevel () { //加载场景 SceneManager.LoadScene (0); } }}
PlayerHealth
using UnityEngine;using UnitySampleAssets.CrossPlatformInput;namespace CompleteProject{    ///     /// 玩家移动    ///     public class PlayerMovement : MonoBehaviour    {        ///         /// 玩家移动速度        ///         public float speed = 6f;                    ///         /// 玩家移动方向        ///         Vector3 movement;                           ///         /// Animator        ///         Animator anim;                              ///         /// Rigidbody        ///         Rigidbody playerRigidbody;          #if !MOBILE_INPUT        ///         /// 地面        ///         int floorMask;                              ///         /// 射线的长度        ///         float camRayLength = 100f;                                    #endif        void Awake ()        {#if !MOBILE_INPUT            floorMask = LayerMask.GetMask ("Floor");#endif            anim = GetComponent 
(); playerRigidbody = GetComponent
(); } void FixedUpdate () { //获取水平和垂直的输入 float h = CrossPlatformInputManager.GetAxisRaw("Horizontal"); float v = CrossPlatformInputManager.GetAxisRaw("Vertical"); //处理玩家的移动 Move (h, v); //处理玩家的旋转 Turning (); //处理玩家的动画 Animating (h, v); } ///
/// 移动 /// ///
///
void Move (float h, float v) { movement.Set (h, 0f, v); //设置移动速度 movement = movement.normalized * speed * Time.deltaTime; //刚体移动 playerRigidbody.MovePosition (transform.position + movement); } ///
/// 旋转 /// void Turning () {#if !MOBILE_INPUT //从鼠标点击的屏幕位置创建射线 Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition); //接收射线撞击到地面的数据 RaycastHit floorHit; //发射射线 if(Physics.Raycast (camRay, out floorHit, camRayLength, floorMask)) { //创建一个玩家到撞击点的向量 Vector3 playerToMouse = floorHit.point - transform.position; //保证这个向量的y为0 playerToMouse.y = 0f; //根据这个向量创建四元数 Quaternion newRotatation = Quaternion.LookRotation (playerToMouse); //刚体旋转 playerRigidbody.MoveRotation (newRotatation); }#else Vector3 turnDir = new Vector3(CrossPlatformInputManager.GetAxisRaw("Mouse X") , 0f , CrossPlatformInputManager.GetAxisRaw("Mouse Y")); if (turnDir != Vector3.zero) { Vector3 playerToMouse = (transform.position + turnDir) - transform.position; playerToMouse.y = 0f; Quaternion newRotatation = Quaternion.LookRotation(playerToMouse); playerRigidbody.MoveRotation(newRotatation); }#endif } ///
/// 播放动画 /// ///
水平输入值 ///
垂直输入值 void Animating (float h, float v) { bool walking = h != 0f || v != 0f; anim.SetBool ("IsWalking", walking); } }}
PlayerMovement
using UnityEngine;using UnitySampleAssets.CrossPlatformInput;namespace CompleteProject{    ///     /// 玩家射击    ///     public class PlayerShooting : MonoBehaviour    {        ///         /// 没发子弹造成的伤害        ///         public int damagePerShot = 20;                          ///         /// 每发子弹的时间间隔        ///         public float timeBetweenBullets = 0.15f;                ///         /// 射击范围        ///         public float range = 100f;                              ///         /// 发射子弹的计时器        ///         float timer;                                            ///         /// 射击射线        ///         Ray shootRay;                                           ///         /// 射击击中点        ///         RaycastHit shootHit;                                    ///         /// 可以受到射击的层        ///         int shootableMask;                                      ///         ///         ///         ParticleSystem gunParticles;                            ///         /// 枪的线条渲染器        ///         LineRenderer gunLine;                                   ///         /// 枪的声音        ///         AudioSource gunAudio;                                   ///         /// 枪的灯光        ///         Light gunLight;                                         ///         ///         ///         public Light faceLight;                                    ///         /// 效果的显示时间        ///         float effectsDisplayTime = 0.2f;                                                                                                                         void Awake ()        {            //获取可以射击的层            shootableMask = LayerMask.GetMask ("Shootable");            gunParticles = GetComponent
(); gunLine = GetComponent
(); gunAudio = GetComponent
(); gunLight = GetComponent
(); //faceLight = GetComponentInChildren
(); } void Update () { //每帧增加计时器的时间 timer += Time.deltaTime;#if !MOBILE_INPUT //如果按下发射按键,计时器大于两次发射子弹的间隔时,时间比例不等于0 if(Input.GetButton ("Fire1") && timer >= timeBetweenBullets && Time.timeScale != 0) { //射击 Shoot (); }#else if ((CrossPlatformInputManager.GetAxisRaw("Mouse X") != 0 || CrossPlatformInputManager.GetAxisRaw("Mouse Y") != 0) && timer >= timeBetweenBullets) { Shoot(); }#endif //如果计时器超过特效显示的时间 if(timer >= timeBetweenBullets * effectsDisplayTime) { //关闭射击效果 DisableEffects (); } } public void DisableEffects () { gunLine.enabled = false; faceLight.enabled = false; gunLight.enabled = false; } ///
/// 射击 /// void Shoot () { //重置计时器 timer = 0f; //播放射击声音 gunAudio.Play (); gunLight.enabled = true; faceLight.enabled = true; //先停止粒子特效,然后再播放特效 gunParticles.Stop (); gunParticles.Play (); //设置线条渲染器的第一个位置 gunLine.enabled = true; gunLine.SetPosition (0, transform.position); //设置 射击射线的 起点和方向 shootRay.origin = transform.position; shootRay.direction = transform.forward; //发射射线,碰到敌人 if(Physics.Raycast (shootRay, out shootHit, range, shootableMask)) { //敌人受到伤害 EnemyHealth enemyHealth = shootHit.collider.GetComponent
(); if(enemyHealth != null) { enemyHealth.TakeDamage (damagePerShot, shootHit.point); } //设置线条渲染器的第二个位置为射击点的位置 gunLine.SetPosition (1, shootHit.point); } //没有碰到敌人,设置线条渲染器的第2个位置 else { gunLine.SetPosition (1, shootRay.origin + shootRay.direction * range); } } }}
PlayerShooting

 

using UnityEngine;namespace CompleteProject{    ///     /// 游戏结束管理    ///     public class GameOverManager : MonoBehaviour    {        ///         /// 玩家生命        ///         public PlayerHealth playerHealth;               ///         /// Animator        ///         Animator anim;                                  void Awake ()        {            anim = GetComponent 
(); } void Update () { //如果玩家生命值小于等于0 if(playerHealth.currentHealth <= 0) { //Animator设置GameOver触发器 anim.SetTrigger ("GameOver"); } } }}
GameOverManager
using UnityEngine;using System.Collections;using UnityEngine.UI;using UnityEngine.Audio;#if UNITY_EDITORusing UnityEditor;#endif/// /// 暂停管理/// public class PauseManager : MonoBehaviour {        public AudioMixerSnapshot paused;    public AudioMixerSnapshot unpaused;        ///     /// Canvas    ///     Canvas canvas;        void Start()    {        canvas = GetComponent
(); } void Update() { //按esc键 切换游戏状态 if (Input.GetKeyDown(KeyCode.Escape)) { canvas.enabled = !canvas.enabled; Pause(); } } ///
/// 暂停游戏 /// public void Pause() { Time.timeScale = Time.timeScale == 0 ? 1 : 0; Lowpass (); } ///
/// 调整声音 /// void Lowpass() { if (Time.timeScale == 0) { paused.TransitionTo(.01f); } else { unpaused.TransitionTo(.01f); } } ///
/// 退出游戏 /// public void Quit() { //调用编辑器的退出 #if UNITY_EDITOR EditorApplication.isPlaying = false; //调用正常的退出 #else Application.Quit(); #endif }}
PauseManager
using UnityEngine;using UnityEngine.UI;using System.Collections;namespace CompleteProject{    ///     /// 玩家分数管理    ///     public class ScoreManager : MonoBehaviour    {        ///         /// 玩家分数        ///         public static int score;                ///         /// 显示玩家分数的文本        ///         Text text;                                                                                                           void Awake ()        {            text = GetComponent 
(); //重置玩家分数 score = 0; } void Update () { //更新玩家分数的显示 text.text = "Score: " + score; } }}
ScoreManager

视频:https://pan.baidu.com/s/1geIxFs3

项目:https://pan.baidu.com/s/1gfDonkf

转载于:https://www.cnblogs.com/revoid/p/6433593.html

你可能感兴趣的文章
七个C#编程的小技巧
查看>>
Android中的AutoCompleteTextView的使用
查看>>
Windows下编译Enigmail源代码
查看>>
《基于MFC的OpenGL编程》Part 11 Blending, Antialiasing and Fog
查看>>
classpath 和 classpath*的 区别:
查看>>
Git~GitLab当它是一个CI工具时
查看>>
RPi 2B 中文语言包
查看>>
7.6. 数值函数
查看>>
OK335xS Ubuntu 12.04.1 版本 Android 开发环境搭建
查看>>
【Android错误集锦】AppBarLayout is overlapping the RecyclerView in one of my xml files.
查看>>
Mybatis入门例子
查看>>
C#进阶系列——DDD领域驱动设计初探(一):聚合
查看>>
4.3. CMD
查看>>
第 16 章 Apache Hbase
查看>>
Linux Autotools
查看>>
【批处理学习笔记】第十三课:常用dos命令(3)
查看>>
笔试题练习(四)
查看>>
大数据的最大价值: 大数据+物体=智能
查看>>
一脸懵逼加从入门到绝望学习hadoop之Caused by: java.net.UnknownHostException: master报错...
查看>>
前端MVC学习总结(二)——AngularJS验证、过滤器、指令
查看>>