耗时一周制作的第一人称射击游戏,希望能帮助到大家!
由于代码较多,分为三篇展示,感兴趣的朋友们可以点击查看!

Unity3D FPS Game:第一人称射击游戏(一)

Unity3D FPS Game:第一人称射击游戏(二)

Unity3D FPS Game:第一人称射击游戏(三)

这里写目录标题

  • 资源
  • 代码
    • FPS_KeyPickUp.cs
    • FPS_LaserDamage.cs
    • FPS_PlayerContorller.cs
    • FPS_PlayerHealth.cs
    • FPS_PlayerInput.cs
    • FPS_PlayerInventory.cs
    • FPS_PlayerParameters.cs
    • HashIDs.cs
    • Tags.cs

资源

链接:https://pan.baidu.com/s/15s8KSN_4JPAvD_fA8OIiCg
想要资源的同学关注公众号输入【FPS】即可获取密码下载资源,这是小编做的公众号,里面有各种外卖优惠券,有点外卖需求的话各位同学可以支持下!

代码

FPS_KeyPickUp.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class FPS_KeyPickUp : MonoBehaviour
{public AudioClip keyClip;                               //钥匙音效public int keyId;                                       //钥匙编号private GameObject player;                              //玩家private FPS_PlayerInventory playerInventory;            //背包private void Start(){player = GameObject.FindGameObjectWithTag(Tags.player);playerInventory = player.GetComponent<FPS_PlayerInventory>();}private void OnTriggerEnter(Collider other){if(other.gameObject == player){AudioSource.PlayClipAtPoint(keyClip, transform.position);playerInventory.AddKey(keyId);Destroy(this.gameObject);}}
}

FPS_LaserDamage.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class FPS_LaserDamage : MonoBehaviour
{public int damage = 20;                        //伤害值public float damageDelay = 1;                  //伤害延迟时间private float lastDamageTime = 0;              //上一次收到伤害的时间private GameObject player;                     //玩家private void Start(){player = GameObject.FindGameObjectWithTag(Tags.player);}private void OnTriggerStay(Collider other){if(other.gameObject == player && Time.time > lastDamageTime + damageDelay){player.GetComponent<FPS_PlayerHealth>().TakeDamage(damage);lastDamageTime = Time.time;}}
}

FPS_PlayerContorller.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public enum PlayerState
{None,                   //初始状态Idle,                   //站立Walk,                   //行走Crouch,                 //蹲伏Run                     //奔跑
}public class FPS_PlayerContorller : MonoBehaviour
{private PlayerState state = PlayerState.None;/// <summary>/// 人物状态设置/// </summary>public PlayerState State{get{if (runing){state = PlayerState.Run;}else if (walking){state = PlayerState.Walk;}else if (crouching){state = PlayerState.Crouch;}else{state = PlayerState.Idle;}return state;}}public float sprintSpeed = 10f;                         //冲刺速度public float sprintJumpSpeed = 8f;                      //冲刺跳跃速度public float normalSpeed = 6f;                          //正常速度public float normalJumpSpeed = 7f;                      //正常跳跃速度public float crouchSpeed = 2f;                          //蹲伏速度public float crouchJumpSpeed = 6f;                      //蹲伏跳跃速度public float crouchDeltaHeight = 0.5f;                  //蹲伏下降高度public float gravity = 20f;                             //重力public float cameraMoveSpeed = 8f;                      //相机跟随速度public AudioClip jumpAudio;                             //跳跃音效public float currentSpeed;                              //当前速度public float currentJumnSpeed;                          //当前跳跃速度private Transform mainCamera;                           //主摄像对象private float standardCamHeight;                        //相机标准高度private float crouchingCamHeight;                       //蹲伏时相机高度private bool grounded = false;                          //是否在地面上private bool walking = false;                           //是否在行走private bool crouching = false;                         //是否在蹲伏private bool stopCrouching = false;                     //是否停止蹲伏private bool runing = false;                            //是否在奔跑private Vector3 normalControllerCenter = Vector3.zero;  //角色控制器中心private float normalControllerHeight = 0f;              //角色控制器高度private float timer = 0;                                //计时器private CharacterController characterController;        //角色控制器组件private AudioSource audioSource;                        //音频源组件private FPS_PlayerParameters parameters;                //FPS_Parameters组件private Vector3 moveDirection = Vector3.zero;           //移动方向/// <summary>/// 初始化/// </summary>private void Start(){crouching = false;walking = false;runing = false;currentSpeed = normalSpeed;currentJumnSpeed = normalJumpSpeed;mainCamera = GameObject.FindGameObjectWithTag(Tags.mainCamera).transform;standardCamHeight = mainCamera.position.y;crouchingCamHeight = standardCamHeight - crouchDeltaHeight;audioSource = this.GetComponent<AudioSource>();characterController = this.GetComponent<CharacterController>();parameters = this.GetComponent<FPS_PlayerParameters>();normalControllerCenter = characterController.center;normalControllerHeight = characterController.height;}private void FixedUpdate(){MoveUpdate();AudioManager();}/// <summary>/// 任务移动控制更新/// </summary>private void MoveUpdate(){//如果在地面上if (grounded){//自身坐标轴的y轴对应世界坐标轴的z轴moveDirection = new Vector3(parameters.inputMoveVector.x, 0, parameters.inputMoveVector.y);//将 direction 从本地空间变换到世界空间moveDirection = transform.TransformDirection(moveDirection);moveDirection *= currentSpeed;//如果玩家输入跳跃if (parameters.isInputJump){//获取跳跃速度CurrentSpeed();moveDirection.y = currentJumnSpeed;//播放跳跃音频AudioSource.PlayClipAtPoint(jumpAudio, transform.position);}}//受重力下落moveDirection.y -= gravity * Time.deltaTime;//CollisionFlags 是 CharacterController.Move 返回的位掩码。//其概述您的角色与其他任何对象的碰撞位置。CollisionFlags flags = characterController.Move(moveDirection * Time.deltaTime);/*CollisionFlags.CollidedBelow   底部发生了碰撞"flags & CollisionFlags.CollidedBelow"返回1;CollisionFlags.CollidedNone    没发生碰撞"flags & CollisonFlags.CollidedNone"返回1;CollisionFlags.CollidedSides   四周发生碰撞"flags & CollisionFlags.CollidedSides"返回1;CollisionFlags.CollidedAbove   顶端发生了碰撞"flags & CollisionFlags.CollidedAbove"返回1;        *///表示在地面上,grounded为truegrounded = (flags & CollisionFlags.CollidedBelow) != 0;//如果在地面上且有移动的输入if (Mathf.Abs(moveDirection.x) > 0 && grounded || Mathf.Abs(moveDirection.z) > 0 && grounded) {if (parameters.isInputSprint){walking = false;crouching = false;runing = true;}else if (parameters.isInputCrouch){walking = false;crouching = true;runing = false;}else{walking = true;crouching = false;runing = false;}}else{if (walking){walking = false;}if (runing){runing = false;}if (parameters.isInputCrouch){crouching = true;}else{crouching = false;}}//蹲伏状态下的角色控制器中心与高度if (crouching){characterController.height = normalControllerHeight - crouchDeltaHeight;characterController.center = normalControllerCenter - new Vector3(0, crouchDeltaHeight / 2, 0);}else{characterController.height = normalControllerHeight;characterController.center = normalControllerCenter;}CurrentSpeed();CrouchUpdate();}/// <summary>/// 根据人物的状态对其速度进行定义/// </summary>private void CurrentSpeed(){switch (State){case PlayerState.Idle:currentSpeed = normalSpeed;currentJumnSpeed = normalJumpSpeed;break;case PlayerState.Walk:currentSpeed = normalSpeed;currentJumnSpeed = normalJumpSpeed;break;case PlayerState.Crouch:currentSpeed = crouchSpeed;currentJumnSpeed = crouchJumpSpeed;break;case PlayerState.Run:currentSpeed = sprintSpeed;currentJumnSpeed = sprintJumpSpeed;break;}}/// <summary>/// 根据人物状态对其脚步声进行定义/// </summary>private void AudioManager(){if(State == PlayerState.Walk){//设置音频源的音高,行走时缓慢audioSource.pitch = 0.8f;if (!audioSource.isPlaying){audioSource.Play();}}else if(State == PlayerState.Run){//设置音频源的音高,奔跑时急促audioSource.pitch = 1.3f;if (!audioSource.isPlaying){audioSource.Play();}}else{audioSource.Stop();}}/// <summary>/// 蹲伏下降与蹲伏上升时相机位置更新/// </summary>private void CrouchUpdate(){if (crouching){if (mainCamera.localPosition.y > crouchingCamHeight){if(mainCamera.localPosition.y-(crouchDeltaHeight * Time.deltaTime * cameraMoveSpeed)< crouchingCamHeight){mainCamera.localPosition = new Vector3(mainCamera.localPosition.x, crouchingCamHeight, mainCamera.localPosition.z); }else{mainCamera.localPosition -= new Vector3(0, crouchDeltaHeight * Time.deltaTime * cameraMoveSpeed, 0);}}else{mainCamera.localPosition = new Vector3(mainCamera.localPosition.x, crouchingCamHeight, mainCamera.localPosition.z);}}else{if (mainCamera.localPosition.y < standardCamHeight){if(mainCamera.localPosition.y + (crouchDeltaHeight * Time.deltaTime * cameraMoveSpeed) > standardCamHeight){mainCamera.localPosition = new Vector3(mainCamera.localPosition.x, standardCamHeight, mainCamera.localPosition.z);}else{mainCamera.localPosition += new Vector3(0, crouchDeltaHeight * Time.deltaTime * cameraMoveSpeed, 0);}}else{mainCamera.localPosition = new Vector3(mainCamera.localPosition.x, standardCamHeight, mainCamera.localPosition.z);}}}
}

FPS_PlayerHealth.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;public class FPS_PlayerHealth : MonoBehaviour
{public bool isDead;                         //是否死亡public float resetAfterDeathTime = 5;       //死亡后重置时间public AudioClip deathClip;                 //死亡时音效public AudioClip damageClip;                //受伤害时音效public float maxHp = 100;                   //生命值上限public float currentHp = 100;               //当前生命值public float recoverSpeed = 1;              //回复生命值速度public Text hpText;private float timer;                        //计时器private FadeInOut fader;                    //FadeInOut组件private FPS_Camera fPS_Camera;private void Start(){currentHp = maxHp;fader = GameObject.FindGameObjectWithTag(Tags.fader).GetComponent<FadeInOut>();fPS_Camera = GameObject.FindGameObjectWithTag(Tags.mainCamera).GetComponent<FPS_Camera>();BleedBehavior.BloodAmount = 0;hpText.text = "生命值:" + Mathf.Round(currentHp) + "/" + Mathf.Round(maxHp);}private void Update(){if (!isDead){currentHp += recoverSpeed * Time.deltaTime;hpText.text = "生命值:" + Mathf.Round(currentHp) + "/" + Mathf.Round(maxHp);if (currentHp > maxHp){currentHp = maxHp;}}if (currentHp < 0){if (!isDead){PlayerDead();}else{LevelReset();}}}/// <summary>/// 受到伤害/// </summary>public void TakeDamage(float damage){if (isDead)return;//播放受伤音频AudioSource.PlayClipAtPoint(damageClip, transform.position);//将值限制在 0 与 1 之间并返回其伤害值BleedBehavior.BloodAmount += Mathf.Clamp01(damage / currentHp);currentHp -= damage;}/// <summary>/// 禁用输入/// </summary>public void DisableInput(){//将敌人相机禁用transform.Find("Player_Camera/WeaponCamera").gameObject.SetActive(false);this.GetComponent<AudioSource>().enabled = false;this.GetComponent<FPS_PlayerContorller>().enabled = false;this.GetComponent<FPS_PlayerInput>().enabled = false;if (GameObject.Find("BulletCount") != null){GameObject.Find("BulletCount").SetActive(false);}fPS_Camera.enabled = false;}/// <summary>/// 玩家死亡/// </summary>public void PlayerDead(){isDead = true;DisableInput();AudioSource.PlayClipAtPoint(deathClip, transform.position);}/// <summary>/// 关卡重置/// </summary>public void LevelReset(){timer += Time.deltaTime;if (timer > resetAfterDeathTime){fader.EndScene();}}
}

FPS_PlayerInput.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class FPS_PlayerInput : MonoBehaviour
{/// <summary>/// 锁定鼠标属性/// </summary>public bool LockCursor{get{//如果鼠标是处于锁定状态,返回truereturn Cursor.lockState == CursorLockMode.Locked ? true : false;}set{Cursor.visible = value;Cursor.lockState = value ? CursorLockMode.Locked : CursorLockMode.None;}}private FPS_PlayerParameters parameters;private FPS_Input input;private void Start(){LockCursor = true;parameters = this.GetComponent<FPS_PlayerParameters>();input = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent<FPS_Input>();}private void Update(){InitialInput();}/// <summary>/// 输入参数赋值初始化/// </summary>private void InitialInput(){parameters.inputMoveVector = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));parameters.inputSmoothLook = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));parameters.isInputCrouch = input.GetButton("Crouch");parameters.isInputFire = input.GetButton("Fire");parameters.isInputJump = input.GetButton("Jump");parameters.isInputReload = input.GetButtonDown("Reload");parameters.isInputSprint = input.GetButton("Sprint");}
}

FPS_PlayerInventory.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class FPS_PlayerInventory : MonoBehaviour
{private List<int> keysArr;          //钥匙列表private void Start(){keysArr = new List<int>();}/// <summary>/// 添加钥匙/// </summary>public void AddKey(int keyId){if (!keysArr.Contains(keyId)){keysArr.Add(keyId);}}/// <summary>/// 是否有对应门的钥匙/// </summary>/// <param name="doorId"></param>/// <returns></returns>public bool HasKey(int doorId){if (keysArr.Contains(doorId))return true;return false;}
}

FPS_PlayerParameters.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;//当你添加的一个用了RequireComponent组件的脚本,
//需要的组件将会自动被添加到game object(游戏物体),
//这个可以有效的避免组装错误
[RequireComponent(typeof(CharacterController))]public class FPS_PlayerParameters : MonoBehaviour
{[HideInInspector]public Vector2 inputSmoothLook;     //相机视角[HideInInspector]public Vector2 inputMoveVector;     //人物移动[HideInInspector]public bool isInputFire;            //是否开火[HideInInspector]public bool isInputReload;          //是否换弹[HideInInspector]public bool isInputJump;            //是否跳跃[HideInInspector]public bool isInputCrouch;          //是否蹲伏[HideInInspector]public bool isInputSprint;          //是否冲刺}

HashIDs.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class HashIDs : MonoBehaviour
{public int deadBool;public int speedFloat;public int playerInSightBool;public int shotFloat;public int aimWidthFloat;public int angularSpeedFloat;private void Awake(){deadBool = Animator.StringToHash("Dead");speedFloat = Animator.StringToHash("Speed");playerInSightBool = Animator.StringToHash("PlayerInSight");shotFloat = Animator.StringToHash("Shot");aimWidthFloat = Animator.StringToHash("AimWidth");angularSpeedFloat = Animator.StringToHash("AngularSpeed");}
}

Tags.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;/// <summary>
/// 封装标签
/// </summary>
public class Tags
{public const string player = "Player";                      //玩家public const string gameController = "GameController";      //游戏控制器public const string enemy = "Enemy";                        //敌人public const string fader = "Fader";                        //淡入淡出的画布public const string mainCamera = "MainCamera";              //主摄像机
}

一个坚持学习,坚持成长,坚持分享的人,即使再不聪明,也一定会成为优秀的人!

整理不易,如果看完觉得有所收获的话,记得一键三连哦,谢谢!

Unity3D FPS Game:第一人称射击游戏(三)相关推荐

  1. Unity3D FPS Game:第一人称射击游戏(一)

    耗时一周制作的第一人称射击游戏,希望能帮助到大家! 由于代码较多,分为三篇展示,感兴趣的朋友们可以点击查看! Unity3D FPS Game:第一人称射击游戏(一) Unity3D FPS Game ...

  2. Unity3D FPS Game:第一人称射击游戏(二)

    耗时一周制作的第一人称射击游戏,希望能帮助到大家! 由于代码较多,分为三篇展示,感兴趣的朋友们可以点击查看! Unity3D FPS Game:第一人称射击游戏(一) Unity3D FPS Game ...

  3. 对金玺曾版《Unity3D手机游戏开发》第三章“第一人称射击游戏”修改,使支持僵尸连续攻击

    我个人觉得这本书写的至少很和我口味,而且他的光盘资料也很详尽,比如,一个实例,不仅有一个完整的实现工程,还有一份供作练习的工程(该工程中没有要练习的部分,而资源啥的都有),让人感觉很好. 这本书下载电 ...

  4. unity3D第一人称射击游戏(推荐)

    unity3d第一人称射击游戏(推荐) 第一部分:简介   这个教程中,我们详细了解下如何制作一个简单的第一人称射击游戏(FPS).其中将介绍一些基本的3D游戏编程的概念和一些关于怎样如游戏程序员般思 ...

  5. 项目实训(十一)——FPS游戏(第一人称射击游戏)初步开发

    一.前言 我与另外两个组员合作进行了FPS游戏(第一人称射击游戏)的开发,这个游戏对应于我们在项目开始设想的PVP玩家对战游戏.玩家之间的之间对战会让游戏变得更加紧张刺激,还能够增强玩家之间的感情. ...

  6. FPS - 第一人称射击游戏

    第一人称射击类游戏,FPS(First-person shooting game), 严格来说第一人称射击游戏属于ACT类游戏的一个分支,但和RTS类游戏一样,由于其在世界上的迅速风靡,使之发展成了一 ...

  7. linux游戏object怎么玩,用Object Detection玩第一人称射击游戏

    在本文中,我将解释如何使用tensorflow的对象检测模型来玩经典的FPS游戏"CS". 不久前,我遇到了这个非常有趣的项目,文章作者使用网络摄像机播放经典的格斗游戏,真人快打. ...

  8. u3d5第一人称射击游戏(C#脚本)完整版并在iOS9.3系统上真机运行

    参考资料:<Unity3D\2D手机游戏开发>(第二版) +   百度 涉及U3D的功能有:摄像机控制.物理.动画.智能寻路等. 开发工具:Unity3D5.3.4,VS2015,VMpl ...

  9. 【转】HTML5第一人称射击游戏发布

    [CSON原创]HTML5第一人称射击游戏发布 功能说明: 游戏中在躲避敌人攻击的同时,需要收集三种不同的钥匙,开启对应的门,最后到达目的地. 该游戏同样基于自己开发的HTML5游戏框架cnGameJ ...

最新文章

  1. Linux经常使用的命令(十) - nl
  2. 流式计算框架Storm后台启动命令(避免新开窗口)
  3. 8086汇编-实验7-制表
  4. Java技术栈---语言基础
  5. ReviewForJob——堆排序
  6. 逆向Android软件的步骤
  7. Net Core平台灵活简单的日志记录框架NLog+SqlServer初体验
  8. bat循环执行带参数_wxappUnpacker的bingo.bat脚本逐行解读
  9. 最详细的U-net论文笔记
  10. Spring Session, Redis 实现微服务 Session 共享
  11. 逻辑读、物理读、预读的理解
  12. 夯实Java基础(十八)——泛型
  13. yum更新php版本,yum安装的php升级到7.0版本
  14. 超星尔雅学习通情商与智慧人生 答案 满分版
  15. 经典商业融资计划书PPT模板
  16. android mapabc 地图 无法 拖动、缩放问题
  17. 程序三大流程:顺序结构、选择结构、循环结构
  18. VRAR行业喷发剃须刀品牌结合VR推广_VRAR123
  19. Tomcat中Session钝化与活化实现步骤
  20. 如何在windows上下载安装zeplin

热门文章

  1. android最新版本 note8,别等了 三星S8和Note 8确认无缘升级Android 10系统
  2. 4. 功耗是如何影响计算机性能的?
  3. 园中有金不在金——大数据的价值
  4. 摸鱼快报:golang net/http中的雕虫小技
  5. 互联网大厂的背景调查,你需要认真对待了!
  6. 爱的力量 --- 悼 5.12 死难同胞, 愿逝者安息, 生者平安!
  7. 如何将Adobe Photoshop CS4 汉化
  8. python3 判断偶数/奇数
  9. 【H5】 echarts绘制条形统计图,饼状图
  10. ChatGPT,又爆了...