1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Unity3D FPS Game:第一人称射击游戏(三)

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

时间:2023-11-19 19:28:54

相关推荐

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

耗时一周制作的第一人称射击游戏,希望能帮助到大家!

由于代码较多,分为三篇展示,感兴趣的朋友们可以点击查看!

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

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

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

这里写目录标题

资源代码FPS_KeyPickUp.csFPS_LaserDamage.csFPS_PlayerContorller.csFPS_PlayerHealth.csFPS_PlayerInput.csFPS_PlayerInventory.csFPS_PlayerParameters.csHashIDs.csTags.cs

资源

链接:/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"; //主摄像机}

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

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。