耗时一周制作的第一人称射击游戏,希望能帮助到大家!
由于代码较多,分为三篇展示,感兴趣的朋友们可以点击查看!
Unity3D FPS Game:第一人称射击游戏(一)
Unity3D FPS Game:第一人称射击游戏(二)
Unity3D FPS Game:第一人称射击游戏(三)
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);
}
}
}
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;
}
}
}
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;
///
/// 人物状态设置
///
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; //移动方向
///
/// 初始化
///
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();
}
///
/// 任务移动控制更新
///
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为true
grounded = (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();
}
///
/// 根据人物的状态对其速度进行定义
///
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;
}
}
///
/// 根据人物状态对其脚步声进行定义
///
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();
}
}
///
/// 蹲伏下降与蹲伏上升时相机位置更新
///
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);
}
}
}
}
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();
}
}
}
///
/// 受到伤害
///
public void TakeDamage(float damage)
{
if (isDead)
return;
//播放受伤音频
AudioSource.PlayClipAtPoint(damageClip, transform.position);
//将值限制在 0 与 1 之间并返回其伤害值
BleedBehavior.BloodAmount += Mathf.Clamp01(damage / currentHp);
currentHp -= damage;
}
///
/// 禁用输入
///
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;
}
///
/// 玩家死亡
///
public void PlayerDead()
{
isDead = true;
DisableInput();
AudioSource.PlayClipAtPoint(deathClip, transform.position);
}
///
/// 关卡重置
///
public void LevelReset()
{
timer += Time.deltaTime;
if (timer > resetAfterDeathTime)
{
fader.EndScene();
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FPS_PlayerInput : MonoBehaviour
{
///
/// 锁定鼠标属性
///
public bool LockCursor
{
get
{
//如果鼠标是处于锁定状态,返回true
return 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();
}
///
/// 输入参数赋值初始化
///
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");
}
}
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>();
}
///
/// 添加钥匙
///
public void AddKey(int keyId)
{
if (!keysArr.Contains(keyId))
{
keysArr.Add(keyId);
}
}
///
/// 是否有对应门的钥匙
///
///
///
public bool HasKey(int doorId)
{
if (keysArr.Contains(doorId))
return true;
return false;
}
}
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; //是否冲刺
}
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");
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///
/// 封装标签
///
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"; //主摄像机
}
一个坚持学习,坚持成长,坚持分享的人,即使再不聪明,也一定会成为优秀的人!
整理不易,如果看完觉得有所收获的话,记得一键三连哦,谢谢!